为什么rowdatabound中的值不会改变

时间:2012-03-20 13:36:21

标签: c# gridview

为什么我不能更改gridview的rowdatabound事件中特定行的值?代码进入值设置为Test的位置但仍显示旧值?

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
    DataKeyNames="au_id" DataSourceID="SqlDataSource1" 
    ondatabinding="GridView1_DataBinding" onrowdatabound="GridView1_RowDataBound">
    <Columns>
        <asp:BoundField DataField="au_id" HeaderText="au_id" ReadOnly="True" 
            SortExpression="au_id" />
        <asp:BoundField DataField="au_lname" HeaderText="au_lname" 
            SortExpression="au_lname" />
        <asp:BoundField DataField="au_fname" HeaderText="au_fname" 
            SortExpression="au_fname" />
    </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:pubsConnectionString %>" 
    SelectCommand="SELECT [au_id], [au_lname], [au_fname] FROM [authors]">
</asp:SqlDataSource>


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var row = ((DataRowView)e.Row.DataItem).Row;

        var customerName = row.Field<String>("au_lname");
        if (customerName == "Carson")
        {
            customerName = "Test";
        }
    } 
}

1 个答案:

答案 0 :(得分:1)

因为您无法在RowDataBound中更改基础数据源(太晚了)。您需要将更改应用于TemplateFields控件或行的CellCollection(如果是BoundFieldsAutogenerateColumns=true):

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataRow row = ((DataRowView)e.Row.DataItem).Row;
        var customerName = row.Field<String>("au_lname");
        if (customerName == "Carson")
        {
            e.Row.Cells[1].Text = "Test";
        }else
        {
            e.Row.Cells[1].Text = customerName;
        }
    }
}