Chiako
Chiako

Reputation: 734

GridView with CheckBox: How To Get Selected Rows in ASP.Net

How to get gridview row values when checkbox is checked. I am using this code in button's click event, but it's not working .

Html Code:

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="100%"
        DataKeyNames="ReportId" OnRowDataBound="GridView2_OnRowDataBound" ForeColor="#333333"
        PageSize="5" Style="text-align: center">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:CheckBox ID="CheckBoxG1" runat="server" />
                </ItemTemplate>

C# Code:

    protected void Button1_Click(object sender, EventArgs e)
{
    foreach (GridViewRow row in GridView1.Rows)
    {
        if (row.RowType == DataControlRowType.DataRow)
        {
            CheckBox CheckRow = (row.Cells[0].FindControl("CheckBoxG1") as CheckBox);
            if (CheckRow.Checked)
            {

            }
        }
    }
}

Upvotes: 3

Views: 11722

Answers (3)

user15019772
user15019772

Reputation:

protected void Button1_Click(object sender, EventArgs e)
{
        int count= 0;
        foreach (GridViewRow gvindex in GridView1.Rows)
        {
            CheckBox chck = gvrow.FindControl("CheckBoxG1") as CheckBox;
            if (chck.Checked)
            {
                GridView1.EditIndex = count;
                DataBind(); //Your Databind Function
            }
            count++;
        }

Upvotes: 0

user3497034
user3497034

Reputation:

In My sample code I have consider manually data while binding gridview because as you don't specify how you have bind your gridview through database or not, but it should work in both approaches. My HTML code

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Get Checkbox Selected Row Values from Gridview in Asp.net</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView ID="gvDetails" DataKeyNames="UserId" AutoGenerateColumns="false" CellPadding="5" runat="server">
                <Columns>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:CheckBox ID="chkSelect" runat="server" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField HeaderText="UserId" DataField="UserId" />
                    <asp:BoundField HeaderText="UserName" DataField="UserName" />
                    <asp:BoundField HeaderText="Education" DataField="Education" />
                    <asp:BoundField HeaderText="Location" DataField="Location" />
                </Columns>
                <HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
            </asp:GridView>
            <asp:Button ID="btnProcess" Text="Get Selected Records" runat="server" Font-Bold="true" onclick="btnProcess_Click" />
            <br />
            <asp:Label ID="lblmsg" runat="server" />
        </div>
    </form>
</body>
</html>

Code Behind: This is just for binding GridView with proper data

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindGridviewData();
    }
}

protected void BindGridviewData()
{
    DataTable dt = new DataTable();
    dt.Columns.Add("UserId", typeof(Int32));
    dt.Columns.Add("UserName", typeof(string));
    dt.Columns.Add("Education", typeof(string));
    dt.Columns.Add("Location", typeof(string));

    DataRow dtrow = dt.NewRow();        //Create New Row
    dtrow["UserId"] = 1;                //Bind Data to Columns
    dtrow["UserName"] = "SureshDasari";
    dtrow["Education"] = "B.Tech";
    dtrow["Location"] = "Chennai";
    dt.Rows.Add(dtrow);

    dtrow = dt.NewRow();               //Create New Row
    dtrow["UserId"] = 2;               //Bind Data to Columns
    dtrow["UserName"] = "MadhavSai";
    dtrow["Education"] = "MBA";
    dtrow["Location"] = "Nagpur";
    dt.Rows.Add(dtrow);

    dtrow = dt.NewRow();              //Create New Row
    dtrow["UserId"] = 3;              //Bind Data to Columns
    dtrow["UserName"] = "MaheshDasari";
    dtrow["Education"] = "B.Tech";
    dtrow["Location"] = "Nuzividu";
    dt.Rows.Add(dtrow);
    
    gvDetails.DataSource = dt;
    gvDetails.DataBind();
}

Code of Button_Click event

protected void btnProcess_Click(object sender, EventArgs e)
{
    string str = string.Empty;
    string strname = string.Empty;
    string edu = string.Empty;
    string location = string.Empty;
    foreach (GridViewRow gvrow in gvDetails.Rows)
    {
        CheckBox chk = (CheckBox)gvrow.FindControl("chkSelect");
        if (chk != null & chk.Checked)
        {
            //To Fetch the row index
            //str += gvDetails.SelectedIndex.ToString();
            
            //To Fetch the value of Selected Row.
            str += gvDetails.DataKeys[gvrow.RowIndex].Value.ToString() + ',';
            strname += gvrow.Cells[2].Text + ',';
            edu += gvrow.Cells[3].Text + ',';
            location += gvrow.Cells[4].Text + ',';
        }
    }
    str = str.Trim(",".ToCharArray());
    strname = strname.Trim(",".ToCharArray());
    lblmsg.Text = "Selected UserIds: <b>" + str + "</b><br/>" + "Selected UserNames: <b>" + strname + "</b><br>" + " Education: <b>" + edu + "</b><br>" + " Location: <b>" + location + "</b><br>";
}

Upvotes: 0

Vasil Akhmetov
Vasil Akhmetov

Reputation: 64

I can not see how you bound data and where is your button placement. So this is work sample.

<asp:Button Text="text" runat="server" OnClick="Unnamed_Click" />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ReportId" Width="100%"
            ForeColor="#333333" PageSize="5" Style="text-align: center">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBoxG1" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            GridView1.DataSource = new RowModel[]
            {
                new RowModel { ReportId = "1" },
                new RowModel { ReportId = "2" },
                new RowModel { ReportId = "3" }
            };

            GridView1.DataBind();
        }
    }

    protected void Unnamed_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow row in GridView1.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                CheckBox CheckRow = (row.Cells[0].FindControl("CheckBoxG1") as CheckBox);
                if (CheckRow.Checked)
                {

                }
            }
        }
    }

public class RowModel
{
    public string ReportId { get; set; }
}

Upvotes: 2

Related Questions