修改特定gridview列的datarow值

时间:2012-02-23 22:19:51

标签: asp.net

如何在列出的gridview事件之一中将IBM的值更改为像思科那样的任意值?

动态网格视图中可能存在不同的列,因此可以按名称对列进行寻址。

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable("TestTable");
            dt.Columns.AddRange(new DataColumn[] { new DataColumn("id"), new DataColumn("customername") });
            DataRow dr = dt.NewRow();
            dr[0] = "1";
            dr[1] = "Microsoft";
            dt.Rows.Add(dr);

            DataRow dr2 = dt.NewRow();
            dr2[0] = "2";
            dr2[1] = "IBM";
            dt.Rows.Add(dr2);

            GridView1.DataSource = dt;
            GridView1.DataBind();

        }

        protected void GridView1_DataBinding(object sender, EventArgs e)
        {

        }

        protected void GridView1_DataBound(object sender, EventArgs e)
        {

        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {

        }

        protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
        {

        }
    }
}

1 个答案:

答案 0 :(得分:2)

AutogenerateColumns设置为true时(默认),此操作无效。您需要以编程方式或声明方式添加列(在aspx标记中)。然后,您可以使用TemplateFieldLabel之类的控件,您可以在代码隐藏中引用它:

例如:

<asp:GridView ID="GridView1" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound" runat="server">
    <Columns>
        <asp:TemplateField HeaderText="Customer">
            <ItemTemplate>
                <asp:Label ID="LblCustomer" runat="server"></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

RowDataBound非常完美(适用于几乎所有事情):

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow) {
        var row = ((DataRowView)e.Row.DataItem).Row;
        var lblCustomer = (Label)e.Row.FindControl("LblCustomer");
        var customerName = row.Field<String>( "customername" );
        if(customerName == "Microsoft") {
            customerName = "Cisco";
        }
        lblCustomer.Text = customerName;
    }
}

修改:好的,永远不需要这样做。但实际上即使将AutoGenerateColumns设置为true,您也可以将 Microsoft 值更改为 Cisco

GridView数据绑定之前触发了

DataBinding事件。如果在数据源绑定到网格之前更改数据源,则可以对其进行修改:

protected void GridView1_DataBinding(object sender, EventArgs e)
{
    var tbl = (DataTable)((GridView)sender).DataSource;
    var msRows = tbl.AsEnumerable()
        .Where(r => r.Field<String>("customername") == "Microsoft")
        .Select(r => r);
    foreach(DataRow msRow in msRows) {
        msRow[ "customername" ] = "Cisco";
    }
}

注意:当然你也可以使用一个简单的循环而不是LINQ