我有GridView(动态创建)和BoundFields。我想在DataBound事件上更改BoundField值。该值包含布尔值(True / False),我需要将它们更改为“Active”/“Inactive”。如果这不是动态GridView,我会使用TemplateField,但是,当我动态创建GridView时,最简单的方法是在BoundField中进行。
但我不明白如何改变它。
这是我正确触发的DataBound事件:
protected void gr_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataRowView drv = (DataRowView)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (drv["IsRegistered"] != DBNull.Value)
{
bool val = Convert.ToBoolean(drv["IsRegistered"]);
//???? HOW TO CHANGE PREVIOUS VALUE TO NEW VALUE (val) HERE?
}
}
}
答案 0 :(得分:6)
使用BoundFields
,您无法使用FindControl
在TemplateField中查找控件以设置其Text
属性。而是设置Cell-Text
:
protected void gr_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataRowView drv = (DataRowView)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (drv["IsRegistered"] != DBNull.Value)
{
bool val = Convert.ToBoolean(drv["IsRegistered"]);
// assuming that the field is in the third column
e.Row.Cells[2].Text = val ? "Active" : "Inactive";
}
}
}
除此之外,您甚至可以在动态TemplateFields
中使用GridView
。
答案 1 :(得分:0)
就我而言,我甚至不知道包含bool值的列的名称或索引。因此,在第一次检查中,我检查单元格的值是否为" True"或者"错误",如果是这样,我记得它的索引。在此之后,我知道索引,如果没有,我什么都不做,如果我找到了,那么我重播它的值。
这是我的工作代码:
// Cache of indexes of bool fields
private List<int> _boolFieldIndexes;
private void gvList_RowDataBound(object sender, GridViewRowEventArgs e)
{
//-- if I checked and there are no bool fields, do not do anything
if ((_boolFieldIndexes == null) || _boolFieldIndexes.Any())
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//-- have I checked the indexes before?
if (_boolFieldIndexes == null)
{
_boolFieldIndexes = new List<int>();
for (int i = 0; i < e.Row.Cells.Count; i++)
{
if ((e.Row.Cells[i].Text == "True") || (e.Row.Cells[i].Text == "False"))
{
// remember which column is a bool field
_boolFieldIndexes.Add(i);
}
}
}
//-- go through the bool columns:
foreach (int index in _boolFieldIndexes)
{
//-- replace its value:
e.Row.Cells[index].Text = e.Row.Cells[index].Text
.Replace("True", "Ja")
.Replace("False", "Nein");
}
}
}
}
好处是,这适用于任何gridview。只需附上活动。