在DataBound事件中更改GridView的BoundField值

3

我有一个动态创建的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?
            }
        } 
    }

这对我来说似乎并不容易。我尝试在网上找一些好的、简单的例子,但是没有找到。另外,对于其他一些列,我需要调用额外的方法来格式化数据。 - renathy
我有一个类似的情况:许多使用绑定字段的网格视图。默认情况下,布尔值呈现为“True”或“False”。我希望将它们翻译成德语,即“Ja”/“Nein”。请参见我的答案... - Tillito
2个回答

6

使用BoundFields时,无法使用FindControlTemplateField中查找控件,例如设置其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";
        }
    } 
} 

除此之外,在动态的GridView中,您甚至可以使用TemplateFields如何通过编程方式添加TemplateField

我也发布了我的代码,它可以在你不知道哪些是布尔字段的情况下工作。 - Tillito

0
在我的情况下,我甚至不知道包含布尔值的列的名称或索引。因此,在第一次尝试中,我检查单元格的值是否为“True”或“False”,如果是,则记住其索引。之后,我知道了索引,如果没有找到,则什么也不做,如果找到了,则替换它的值。
这是我的工作代码:
// 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");
            }
        }
    }
}

好处是,这适用于任何网格视图。只需附加事件即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接