Friday 29 March 2013

et a Multiple selected Values from a Gridview using Asp.Net


get a Multiple selected Values from a Gridview using Asp.Net


In this article we will see have the check box inside GridView control to select the multiple values and the selected value will be displayed. As we have seen in your mail client like hotmail,Gmail and other mail client.
First Drag and Drop one Gridvew and Button on asp Page.Later Retrieve the Data From a Table on Gridview,by using Bound field and Add on CheckBox field in .aspx source code page as Below.
<asp:GridView id="Gridview1" runat ="server" AutoGenerateColumns ="False" ShowFooter ="True"  DataSourceID ="SqlDataSource1" OnSelectedIndexChanged="Gridview1_SelectedIndexChanged" style="z-index: 101; left: 19px; position: absolute; top: 142px" BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px" CellPadding="2" ForeColor="Black" GridLines="None" Width="240px" >

<Columns >
<asp:TemplateField >
<ItemTemplate >
<asp:CheckBox ID="chk" runat ="server" />
ItemTemplate>
asp:TemplateField>

<asp:BoundField  DataField ="ID" HeaderText ="ID" />
<asp:BoundField DataField="empname" HeaderText ="Name" />
<asp:BoundField DataField ="salary" HeaderText ="Salary" />

Columns>
    <FooterStyle BackColor="Tan" />
    <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
    <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />
    <HeaderStyle BackColor="Tan" BorderColor="Fuchsia" BorderStyle="Solid" Font-Bold="True" />
    <AlternatingRowStyle BackColor="PaleGoldenrod" />
asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
            ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>" SelectCommand="SELECT [ID], [empname], [salary] FROM [emp]">
        asp:SqlDataSource>
The output Image of Above code is Below: 
Now i am writing code in GetValues Button to retrive values when the user selects one or more CheckBoxes.
protected void GetValues_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < Gridview1.Rows.Count; i++)
        {
            CheckBox chkb = (CheckBox)Gridview1.Rows[i].Cells[0].FindControl("chk");
            if (chkb.Checked)
            {
                string name = Gridview1.Rows[i].Cells[2].Text;
                Response.Write(" " + name);
            }
        }
    }

Click on GetValues Button After selecting one or more CheckBoxes, then you will get Values what you had checked in gridview.
The OutPut Of Image is Below:

No comments:

Post a Comment