Get GridView Selected Row on Button Click Event
Get GridView Selected Row on Button Click Event
Step 1: Design web form .aspx Page
<div>
<asp:GridView ID="gr" runat="server"
DataKeyNames="Name"
AutoGenerateColumns="false"
AlternatingRowStyle-BackColor="WhiteSmoke"
Width="40%"
OnRowDataBound="gr_RowDataBound"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<HeaderStyle BackColor="#3366ff"
Font-Bold="true"
ForeColor="White"
/>
<Columns>
<asp:BoundField DataField="Name"
HeaderText="Name"
/>
<asp:BoundField DataField="City"
HeaderText="City"
/>
<asp:BoundField DataField="Phone"
HeaderText="Phone"
/>
<asp:CommandField SelectText="Select"
ShowSelectButton="true"
Visible="false"
/>
</Columns>
</asp:GridView>
<asp:Button ID="BTnFetchRow"
runat="server"
Text="Show
Value" OnClick="BTnFetchRow_Click" />
<asp:HiddenField ID="hd" runat="server"
/>
</div>
Step 2:Logic on .Cs page
public void bind_gr()
{
DataTable dt = new
DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("City");
dt.Columns.Add("Phone");
dt.Columns.Add("percentage");
dt.Rows.Add("Kandy", "Delhi", "8802***2564",
"54");
dt.Rows.Add("Sam", "Hr", "545502*2544",
"32");
dt.Rows.Add("Izhar", "Up", "95802*2452",
"90");
dt.Rows.Add("Vineet", "Delhi", "88022564***",
"31");
gr.DataSource = dt;
gr.DataBind();
}
protected void
gr_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onclick"]
= Page.ClientScript.GetPostBackClientHyperlink(this.gr,
"Select$" + e.Row.RowIndex);
e.Row.ToolTip = "Click to select this row.";
}
}
protected void
GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
string Name = gr.SelectedDataKey.Value.ToString();
string City = gr.SelectedRow.Cells[1].Text;
hd.Value = Name;
foreach (GridViewRow
row in gr.Rows)
{
if (row.RowIndex == gr.SelectedIndex)
{
row.BackColor = ColorTranslator.FromHtml("Yellow");
row.ToolTip = string.Empty;
}
else
{
row.BackColor = ColorTranslator.FromHtml("#FFFFFF");
row.ToolTip = "Click to select this
row.";
}
}
}
protected void
BTnFetchRow_Click(object sender, EventArgs e)
{
Response.Write(hd.Value);
}
Comments
Post a Comment