Thursday, 23 June 2011

How to use Check Box in Gridview in Asp.Net

ASP.net with C#
Take a GridView, Connect it to a table.

  •  Go to the 'Edit-Columns' of the GridView. 
  •  Add a 'template-field' 
  •  Hit OK. 
  •  Now, go to the 'Edit-Template' of the GridView. 
  •  In the 'Column[0]' of the Item-Template, drag-drop a CheckBox 
  •  Check out whats the ID of the CheckBox (must be CheckBox1) 
  •  That's it. 

Now Stop 'Editing Template' In the Code-Behind use the following code :

// Add Button code
//GridView1 is Gridview control ..
protected void buttonAdd_Click(object sender, EventArgs e)
{
  // Iterating through Gridview rows
  foreach (GridViewRow gvr in GridView1.Rows)
  {
    // Finding checkbox in a row of data grid control
    CheckBox cb = (CheckBox)gvr.FindControl("CheckOne");
    if (cb.Checked == true)
    {
      // Action to be taken if check box is checked
      Response.Write("<h1>Checked !!</h1>");
    }
  }
}