Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional output in cell based on row data in Gridview's RowDataBound event

i have a bit value (Black) i want to display its status in gridview as if its true, the row display "Yes", otherwise the row display "No", this is my code, but the result is not right, cuz my code display all rows "Yes" if one value is true, i want to display each row status

    protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataTable dt = GetData();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                Boolean bitBlack = Convert.ToBoolean(dt.Rows[i]["Black"]);
                if (bitBlack)
                {
                    e.Row.Cells[7].Text = ("Yes");
                }
                else
                {
                    e.Row.Cells[7].Text = ("No");
                }
            }
        }
    }
like image 301
Shehab Avatar asked Mar 12 '12 12:03

Shehab


Video Answer


3 Answers

You could always use the rows DataItem to get the underlying DataSource:

protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataRow row = ((DataRowView)e.Row.DataItem).Row;
        bool isBlack = row.Field<bool>("Black");
        e.Row.Cells[7].Text = isBlack ? "Yes" : "No";
    }
}
like image 146
Tim Schmelter Avatar answered Sep 29 '22 03:09

Tim Schmelter


I don't know your datasource, but if you can evaluate it, do something like this:

<asp:TemplateField HeaderText="Status">
            <ItemStyle CssClass="list" />
            <ItemTemplate>
                    <%# GetBit(Eval("BlackBit"))%>
            </ItemTemplate>
</asp:TemplateField>

And code-behind:

private string GetBit(object objBit)
{
    if (Convert.ToInt32(objBit) == 1)
    {
        return "Yes";
    }
    return "No";
}
like image 42
Thomas Avatar answered Sep 29 '22 02:09

Thomas


Do you need to iterate through a DataTable dt on each RowDatabound ?

If you do not need this could you try:

protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

                Boolean bitBlack = Convert.ToBoolean(e.Row.Cells[7].Text);
                if (bitBlack)
                {
                    e.Row.Cells[7].Text = "Yes";
                }
                else
                {
                    e.Row.Cells[7].Text = "No";
                }

        }
    }
like image 38
Seany84 Avatar answered Sep 29 '22 03:09

Seany84