C# 基于Gridview的RowDataBound事件中的行数据的单元格中的条件输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9666844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Conditional output in cell based on row data in Gridview's RowDataBound event
提问by Shehab
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
我有一个位值(黑色)我想在 gridview 中显示它的状态,好像它是真的,行显示“是”,否则行显示“否”,这是我的代码,但结果不正确,因为我的代码显示所有行“是”如果一个值为真,我想显示每一行状态
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");
}
}
}
}
采纳答案by Tim Schmelter
You could always use the rows DataItemto get the underlying DataSource:
您始终可以使用行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<bool>("Black");
e.Row.Cells[7].Text = isBlack ? "Yes" : "No";
}
}
回答by Seany84
Do you need to iterate through a DataTable dt on each RowDatabound ?
您是否需要遍历每个 RowDatabound 上的 DataTable dt?
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";
}
}
}
回答by Thomas
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";
}

