Monday, June 11, 2007

Multi Row Selection in GridView

It some cases you want to have the ability to select mutli rows in GridView. By default it can not be done in GridView, but you can have a CheckBox for each row in your GridView and then users can select two or more row by checking the CheckBoxes.

So, after you created your GridView and binding that to a DataSource. You can add a TemplateColumn in your GirdView as the first Column. Like this:


<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>

Then you can have the selected rows index with these lines of code:

private int[] GetSelectedIndices()
{
ArrayList indicesList = new ArrayList();
for(int i = 0 ; i <>
{
GridViewRow row = GridView1.Rows[i];
// 0 means the first column if your Select column is not first write it 's correct index
CheckBox chk = row.Cells[0].FindControl("chkSelect") as CheckBox;
if(chk != nul && chk.Checked)
indeicesList.Add(i);
}
return (int[]) indicesList.ToArray(typeof(int));
}

you can find sample code here:
http://www.tabatabaei.info/csharpsamples/mutlirowselectgrid.zip