0

I have a GridView populated from an XML file. I have added an id=chkRow column to this list. There are over 100 records/rows.

What I want to do ultimately is limit the number of rows/checkboxes that the user can click to three.

I have successfully figured out how to increment an integer everytime a checkbox is changed - but it keeps incrementing even if I uncheck.

So now, what I want to do is increment when the selected row is Checked=true, and decrease when Checked=false.

I am unable to figure out how to get the checked state of the checkbox that was just clicked.

This code throws a NullReferenceException when I click on any checkbox.

protected void MyCheckBoxes_SelectedIndexChanged(object sender, EventArgs e)
        {  
             CheckBox chk1 = (CheckBox)GridView1.HeaderRow.FindControl("chkRow");
                Label1.Text = mycount.ToString();
                if(chk1.Checked == true)

                       {
                           Increment();
                       }

        }
Maureen
  • 207
  • 1
  • 4
  • 11
  • Check out the `sender` object. For events like this, that object is the control this event is for. [More info.](http://stackoverflow.com/a/1303176/3711928) – j.f. Sep 08 '16 at 20:55

2 Answers2

0

Try this. (Assuming your checkboxes are in the first column)

        private void dataGridView1_CellContentClick(object sender,DataGridViewCellEventArgs e)
        {
        int checks = 0;
        foreach (DataGridViewRow Row in dataGridView1.Rows)
        {
            if (Convert.ToBoolean(Row.Cells[0].Value) == true)
                checks++;
        }   
            if (checks == 3  && Convert.ToBoolean(dataGridView1.CurrentCell.Value == false)
                return;
        }
Robert Altman
  • 161
  • 11
0

You can find the Checkbox :

int  checks=0;
 foreach (GridViewRow row in GridView1.Rows)
{
    if (row.RowType == DataControlRowType.DataRow)
    {
        CheckBox chkRow = (row.Cells[0].FindControl("chkRow") as CheckBox);
        if (chkRow.Checked)
        {

                checks++;
        }   
            if (checks == 3)
                return;
        }
    }
}
Hina Khuman
  • 757
  • 3
  • 14
  • 41