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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15696551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:37:43  来源:igfitidea点击:

Setting a Textbox value within a GridView template field

c#asp.netdatagridview

提问by user1352057

Within my load method of my page i want to set the Textbox in a templatefield to a value.

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

Here is my current source code showing my template field textbox item 'txtQuan':

这是我当前的源代码,显示了我的模板字段文本框项“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>

And this is how im trying to set the TextBox value:

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

 string cartQty = Qty.ToString();

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

Im currently receiving a 'nullRefernceException error'.

我目前收到“nullReferenceException 错误”。

采纳答案by codingbiz

Use the RowDataBound event to do that. You can look that up on the internet. The arguments to that event handler gives you easy access to each row. You can also loop through the rows using var rows = myGridView.Rows

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

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

For the event: GridView RowDataBound

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

回答by Mudassir Hasan

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