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");
}
}
}
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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";
}
}
Method 2
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";
}
Method 3
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";
}
}
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0