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

标签 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>

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

 string cartQty = Qty.ToString();

 ((TextBox)(FindControl("txtQuan"))).Text = cartQty;

我目前收到“nullRefernceException 错误”。

最佳答案

使用 RowDataBound 事件来做到这一点。你可以在网上查一下。该事件处理程序的参数使您可以轻松访问每一行。您还可以使用 var rows = myGridView.Rows

遍历行
var rows = myGridView.Rows;
foreach(GridViewRow row in rows)
{
    TextBox t = (TextBox) row.FindControl("txtQuan");
    t.Text = "Some Value";
}

对于事件: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";    
    }   
  }

关于c# - 在 GridView 模板字段中设置文本框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15696551/

相关文章:

c# - 以编程方式添加到 DataGridView 单元格的 ComboBox 在单元格单击时不展开

c# - 有没有办法省略参数?

c# - 数据库/数据网格上的插入和更新语法错误

c# - 提取定界符之间的文本行并将它们添加到 List<string>

javascript - asp.net 中的 HTML 标记注入(inject)

c# - 从 dataGridView 到 TextBox,取 headername

c# - Elasticsearch.NET和NEST-搜索总是返回0个结果

c# - 哪个是更好的选择? - 在 Web 控件的 Viewstate 中的局部变量或存储变量

c# - 有关 ASP.NET 2.0 应用程序设计的问题

c# - 如何在 WinForms 的 DataGridView 中显示 JSON 数据?