2

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

2
  • In which event are you setting that value? You need to find the row in which the textbox belongs and call row.FindControl(...)
    – codingbiz
    Commented Mar 29, 2013 at 2:51
  • @codingbiz Thanks for your answer. I want to set a textbox for each row of my gridview as it will be used to allow the user to adjust the quanity of an item.I then want to populate each textbox based on the cartQty value. I have tried to set a row object by using GridViewRow row = GridView1.SelectedRow; but abviously i have not selected a row. Commented Mar 29, 2013 at 3:10

2 Answers 2

5

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";    
    }   
  }
0
2
((TextBox)grdviewId.Row.FindControl("txtQuan")).Text=cartQty;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.