基于Gridview的RowDataBound事件中的行数据的单元格中的条件输出
我有一点值(黑色)我想在gridview中显示它的状态,如果它是真的,行显示“是”,否则行显示“否”,这是我的代码,但结果不对,因为我的代码显示所有行“是”如果一个值为true,我想显示每一行的状态
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"); } } } }
您始终可以使用行DataItem
来获取基础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("Black"); e.Row.Cells[7].Text = isBlack ? "Yes" : "No"; } }
我不知道您的数据源,但如果您可以评估它,请执行以下操作:
<%# GetBit(Eval("BlackBit"))%>
代码隐藏:
private string GetBit(object objBit) { if (Convert.ToInt32(objBit) == 1) { return "Yes"; } return "No"; }
你需要在每个RowDatabound上遍历DataTable dt吗?
如果您不需要,可以尝试:
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"; } } }