There are many instances when we require a webcontrol like a checkbox to be added to a datagrid for performing different operations like adding or deleting records available in a datagrid(from a shopping cart or a mailbox). This articles demonstrates how to add a checkbox to a datagrid and read whether the checkbox is checked for each of the records present in the datagrid and perform specific action on them. Code below shows a datagrid which contains a checkbox column and a checkbox column is added to the datagrid within the TemplateColumn tag and precisely in the ItemTemplate tag of the datagrid. It is added as a normal checkbox server control.
In this example we have added a button to read all the records which have been selected by checking the respective boxes in each record and display the checked records. In the code behind, we bind the data to the datagrid as shown below:
private void Page_Load(object sender, System.EventArgs e) { if(!Page.IsPostBack) { adp = new SqlDataAdapter("Select * from customers",con); ds= new DataSet(); adp.Fill(ds); DGSample.DataSource=ds; DGSample.DataBind();
}
}
And in the button click event for the button, we write the code for processing the records having checked boxes. In a loop for each item present in the datagrid, we find the check box control which we have added in the ItemTemplate tag and assign to an instance of a checkbox variable. For each of this checkbox we check whether the box is checked and if so we perform the required action on the checked records.
private void Button1_Click(object sender, System.EventArgs e) { CheckBox chkbox = new CheckBox(); TextBox txtbox= new TextBox(); foreach(DataGridItem item in DGSample.Items ) { chkbox=(CheckBox)item.FindControl("chkbox"); txtbox=(TextBox)item.FindControl("txtbox"); if(chkbox.Checked) { Response.Write(item.Cells[0].Text); // write the required code for processing the checked // records depending on the requirement. } }
}