Nanda
Nanda

Reputation: 614

How to get checkbox value in gridview

Can you please help me on this, I get the check box control value as false always even when I check the control in gridview.

for (int i = 0; i < GridView1.Rows.Count; i++)
{
    CheckBox CheckBox1 = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");

    if (CheckBox1 != null)
    {
        if (CheckBox1.Checked)
        {
            query = GridView1.Rows[i].FindControl("Label1") + ",";
        }
    }
}

Upvotes: 2

Views: 9326

Answers (2)

Himanshu
Himanshu

Reputation: 716

Inside the checkbox design add the following attribute

ToolTip="<%#Container.DataItemIndex+1 %> " and then following is the code behind

for (int i = 0; i < gdview.Rows.Count; i++)
    {
        string labeldetail = "";

        CheckBox cbox = (CheckBox)gdview.Rows[i].Cells[0].FindControl("CheckBox1");

        if (cbox != null)
        {
            if (cbox.Checked == true)
            {

                int rowsNo = (Convert.ToInt16(city.ToolTip) - 1); //Convert.ToInt16(SrNo);
               labeldetail = ((Label)gdview.Rows[rowsNo].FindControl("labelid")).Value;

}

Upvotes: 0

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102368

Are you databinding on Page_Load method? If yes, you must do this:

if(!IsPostBack)
{
    GridView1.DataSource = YourData;
}

If you don't do this, your DataGridView will be databound even if it is a PostBack. This way no matter what you checked, the DataGridView will be repopulated from the data source for your postbacks.

Using the above code, when you do if(!IsPostBack), it will retain the checkbox's viewstate value and you get the correct Checked status.

Upvotes: 2

Related Questions