Conditional output in a cell based on row data in the Gridview RowDataBound event

I have a bit (black). I want to display its status in gridview, as if its true, the line displayed "Yes", otherwise the line "No", this is my code, but the result is wrong, because my code displays all the lines "Yes", if one value is true I want to display each line 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"); } } } } 
+6
source share
3 answers

You can always use the DataItem strings 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"; } } 
+9
source

Do you need to iterate over a DataTable dt for each RowDatabound?

If you do not need this, you can 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"; } } } 
+2
source

I do not know your data source, but if you can evaluate it, do the following:

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

And the code:

 private string GetBit(object objBit) { if (Convert.ToInt32(objBit) == 1) { return "Yes"; } return "No"; } 
+2
source

Source: https://habr.com/ru/post/910493/


All Articles