在GridView模板字段中设置文本框值

use*_*057 2 c# asp.net datagridview

在我的页面加载方法中,我想将模板字段中的文本框设置为值.

这是我当前的源代码,显示了我的模板字段文本框项'txtQuan':

    <asp:TemplateField>
              <ItemTemplate>
              <asp:Label ID="lblTotalRate" Text="Qty:" runat="server" />
              <asp:TextBox ID="txtQuan" Height="15" Width="30" runat="server" />

              <asp:Button ID="addButton" CommandName="cmdUpdate" Text="Update Qty"  OnClick="addItemsToCart_Click" runat="server" />
             </ItemTemplate>
             </asp:TemplateField>
Run Code Online (Sandbox Code Playgroud)

这就是我试图设置TextBox值的方式:

 string cartQty = Qty.ToString();

 ((TextBox)(FindControl("txtQuan"))).Text = cartQty;
Run Code Online (Sandbox Code Playgroud)

我当前收到'nullRefernceException错误'.

cod*_*biz 5

使用RowDataBound事件来执行此操作.你可以在互联网上查看.该事件处理程序的参数使您可以轻松访问每一行.您还可以使用循环遍历行var rows = myGridView.Rows

var rows = myGridView.Rows;
foreach(GridViewRow row in rows)
{
    TextBox t = (TextBox) row.FindControl("txtQuan");
    t.Text = "Some Value";
}
Run Code Online (Sandbox Code Playgroud)

对于事件:GridView RowDataBound

  protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e)
  {

    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        TextBox t = (TextBox) e.Row.FindControl("txtQuan");
        t.Text = "Some Value";    
    }   
  }
Run Code Online (Sandbox Code Playgroud)