Get grdiview checkbox Selected value in Asp.net

Get grdiview checkbox Selected value in Asp.net

Step 1: Design web page .aspx


       <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="Select">
                        <ItemTemplate>
                            <asp:CheckBox ID="chk_select" runat="server" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="Name" HeaderText="Name" />
                    <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="gtn_get" runat="server" Text="Get Value" BackColor="YellowGreen" OnClick="gtn_get_Click" />
        </div>


Step 2: Logic on .CS page

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind_gr();
        }
    }
    protected void gtn_get_Click(object sender, EventArgs e)
    {
        string id = string.Empty;
        string Name = string.Empty;
        foreach (GridViewRow gvr in gr.Rows)
        {
            CheckBox chk_sl = (CheckBox)gvr.FindControl("chk_select");
            if (chk_sl.Checked)
            {
                id += gvr.Cells[1].Text + ',';
                Name += gvr.Cells[2].Text + ',';
            }
        }

        id = id.Trim(",".ToCharArray());
        Name = id.Trim(",".ToCharArray());

        Response.Write("City =" + id);
        Response.Write("Name =" + Name);
    }

    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***");


        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();

    }


It will look like :-





Comments

Popular posts from this blog

Create and save QR code in asp.net with C#

Change text of RadGrid Header Dynamically

Telerik Radwindow Open on Button Click