2012-03-20 16 views
1

爲什麼我無法更改gridview的rowdatabound事件中特定行的值?代碼正在輸入值設置爲Test的位置,但仍顯示舊值?爲什麼rowdatabound中的值沒有變化

<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"; 
     } 
    } 
} 
+0

您要更改客戶名稱變量值不是行中的數據。 – 2012-03-20 13:39:46

回答

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; 
     } 
    } 
} 
+0

感謝您的洞察! – Rod 2012-03-21 01:36:02