KyLim KyLim - 1 month ago 13
ASP.NET (C#) Question

c# get value from gridview

<asp:TemplateField HeaderText="Employee ID" HeaderStyle-BackColor="#0033cc" HeaderStyle-ForeColor="White" ItemStyle-Width="10%">
<ItemTemplate>
<asp:Label runat="server" ID="ONE" Text='<%#Eval("REG_ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" HeaderStyle-BackColor="#0033cc" HeaderStyle-ForeColor="White" ItemStyle-Width="20%">
<ItemTemplate>
<asp:Label runat="server" ID="TWO" Text='<%#Eval("Name") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="View" HeaderStyle-BackColor="DarkBlue" HeaderStyle-ForeColor="White" ItemStyle-Width="5%">
<ItemTemplate>
<asp:LinkButton ID="report" class="btn btn-warning btn-sm" Text="Report to HR" runat="server" OnClick="report_Click" />
</ItemTemplate>
</asp:TemplateField>


Above is the code of my GridView. I want get the value of A and B from the GridView when I click the button. Any ideas how to perform this?

protected void report_Click(object sender, EventArgs e)
{
GridViewRow theClickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
if (theClickedRow != null)
{
Label FIRST = theClickedRow.FindControl("ONE") as Label;
Label SECOND = theClickedRow.FindControl("TWO") as Label;
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + FIRST + SECOND + "');", true);

}
}


RESULT I get always : system web ui controlsystem web ui control

Answer

FIRST and SECOND are Label objects. When you call "alert('" + FIRST + SECOND + "');", you are printing the actual objects instead of the values of these controls.

Label controls have a .Text property which allows you to access the text content value.

Your code should be changed to the following:

ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + FIRST.Text + SECOND.Text + "');", true);