为DataGrid添加一个选择列
1:在HTML中为DataGrid定义一个选择列
<asp:TemplateColumn HeaderText="选择">
<ItemTemplate>
<asp:CheckBox id="cbSelect" runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>
2:获取所有选择的行,做相应的处理
public static ArrayList GetDataGridSelectedKeys( DataGrid dg,string checkboxName)
{
ArrayList arr = new ArrayList();
int recordCount = dg.Items.Count;
DataGridItem dgi;
System.Web.UI.WebControls.CheckBox cb;
for (int i=0; i<recordCount; i++)
{
dgi = dg.Items[i];
cb = (CheckBox)dgi.FindControl(checkboxName);
if (cb.Checked)
{
arr.Add(dg.DataKeys[i].ToString());
}
}
return arr;
}
3:通过一个checkbox按钮处理选择/取消所有记录
private void ckSelectAll_CheckedChanged(object sender, System.EventArgs e)
{
foreach(DataGridItem thisItem in dgRecord.Items)
{
((CheckBox)thisItem.Cells[0].Controls[1]).Checked = ckSelectAll.Checked;
}
}