0

I created a gridview containing textbox that are populated in the backend:

<asp:GridView ID="grvMyTest" runat="server" AutoGenerateColumns="False"
EnableModelValidation="True" Height="30%" TabIndex="9" 
AllowSorting="True" Width="100%" Visible="true" AllowPaging="True" 
PageSize="20" CssClass="mGrid" PagerStyle-CssClass="pgr">
  <Columns>
     <asp:TemplateField HeaderText="Jan">
        <ItemTemplate>
           <asp:TextBox ID="tbjan" runat="server" Text='<%# Eval("mJan") %>' 
              Width="50px" style="text-align: center"></asp:TextBox>
        </ItemTemplate>
      <HeaderStyle BackColor="Control" HorizontalAlign="Center" />
      <ItemStyle HorizontalAlign="Center" />
   </asp:TemplateField>

In the backend I would like that when the user clicks the button I would like to retrieve the value of the TextBox to update in the database:

<asp:Button runat="server" Text="Alter values" id="testButton" OnClick="clickedButton" />

Back-end code:

protected void clickedButton(object sender, System.EventArgs e)
{
  foreach (GridViewRow row in grvMyTest.Rows) //Running all lines of grid
  {
      TextBox value = ((TextBox)(row.Cells[0].FindControl("mJan")));
   }
}

But the value is always null even having given in the database that appear on the grid.

When the page loads the values appear: Grid But, the value is null when the button as clicked (clickedButton method).

2
  • 1
    TextBox value = ((TextBox)(row.FindControl("tbjan"))); Commented Feb 14, 2019 at 18:17
  • Thanks @vdwwd ! But, the code retrieves the value set in Bind. I would like it to recover what the user changed. For example, the original value of the cell is 10, and the user changes to 11 in the TextBox. When the button is pressed, I want the value 11, not 10. Commented Feb 14, 2019 at 18:27

2 Answers 2

1

A very quick and simple solution would be to add a Label to the GridView and set it's Visiblity to false.

<asp:TextBox ID="tbjan" runat="server" Text='<%# Eval("mJan") %>'></asp:TextBox>
<asp:Label ID="tbjanLabel" runat="server" Text='<%# Eval("mJan") %>' Visible="false"></asp:Label>

Then you can compare those values in code behind

 TextBox value = (TextBox)(row.FindControl("tbjan"));
 Label lbl = (Label)(row.FindControl("tbjanLabel"));

 if (lbl.Text == value.Text)
 {
     //no change
 }
Sign up to request clarification or add additional context in comments.

1 Comment

It was exactly what she needed, thank you very much for the help.
0

Complementing the VDWWD response, make sure the page is not calling the postback and missing the references from the gridview.

1 Comment

The postback was occurring earlier, clearing what the user had inserted into the grid. Thanks.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.