user1352057
user1352057

Reputation: 3182

Setting a Textbox value within a GridView template field

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':

    <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:

 string cartQty = Qty.ToString();

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

Im currently receiving a 'nullRefernceException error'.

Upvotes: 2

Views: 25902

Answers (2)

codingbiz
codingbiz

Reputation: 26376

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

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

For the event: 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";    
    }   
  }

Upvotes: 5

Mudassir Hasan
Mudassir Hasan

Reputation: 28741

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

Upvotes: 2

Related Questions