Fetch Gridview rows value on button click
Fetch Gridview rows value on button click
Step 1: Design web from .aspx page
<div>
<asp:GridView ID="gr" runat="server" AutoGenerateColumns="false" AlternatingRowStyle-BackColor="WhiteSmoke" Width="40%">
<HeaderStyle BackColor="#3366ff" Font-Bold="true" ForeColor="White" />
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lbl_Name" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="City" HeaderText="City" />
<asp:TemplateField HeaderText="Phone">
<ItemTemplate>
<asp:Label ID="lbl_phone" runat="server" Text='<%#Eval("Phone") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btn_chk" runat="server" Text="Fetch" OnClick="btn_chk_Click" BackColor="YellowGreen" />
</div>
Step 2 : Logic on .Cs page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Bind
Gridview
bind_gr();
}
}
public void bind_gr()
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("City");
dt.Columns.Add("Phone");
dt.Rows.Add("Kandy", "Delhi", "8802***2564");
dt.Rows.Add("Sam", "Hr", "545502*2544");
dt.Rows.Add("Izhar", "Up", "95802*2452");
dt.Rows.Add("Vineet", "Delhi", "88022564***");
gr.DataSource = dt;
gr.DataBind();
}
protected void btn_chk_Click(object sender, EventArgs e)
{
string name=string.Empty;
string phone = string.Empty;
foreach (GridViewRow gvr in gr.Rows)
{
Label lbl_Name = gvr.FindControl("lbl_Name") as Label;
Label lbl_phone = gvr.FindControl("lbl_phone") as Label;
name += lbl_Name.Text+",";
phone += lbl_phone.Text + ",";
}
Response.Write(name);
Response.Write("<BR/>");
Response.Write(phone);
}
Comments
Post a Comment