为DataGrid创建自定义列控件(四)
全选和多选的功能在DataGrid中使用的时候很多,以前我们都是创建CheckBox模板列,然后在后台中捕获ChecnkBox的选择情况来实现全选或多选.现在为了加快开发的速度,使用这个CheckBoxColumn列控件,可以很方便的实现多选或全选的功能.
代码如下:
看过我前面几篇列控件介绍的朋友对上面的代码一定不会有什么问题.
首先还是在DataGrid中引用这个列控件,方法和以前一样,这里就不多说了.
然后看看具体的使用:
代码如下:
CheckBoxColumn
看过我前面几篇列控件介绍的朋友对上面的代码一定不会有什么问题.
首先还是在DataGrid中引用这个列控件,方法和以前一样,这里就不多说了.
然后看看具体的使用:
- 获得选择行的Index值
CheckBoxColumn chkColumn = (CheckBoxColumn)this.DataGrid1.Columns[0];
foreach(object index in chkColumn.SelectIndexes)//SelectIndexes获得选择的Index值
{
Response.Write(index.ToString()+"<br>");
} - 获得选择行的DataKeys值
CheckBoxColumn chkColumn = (CheckBoxColumn)this.DataGrid1.Columns[0];
foreach(object index in chkColumn.SelectedDataKeys)//SelectedDataKeys获得选择的DataKeys值
{
Response.Write(index.ToString()+"<br>");
} - 获得未选择行的Index值和获得未选择行的DataKeys值
CheckBoxColumn chkColumn = (CheckBoxColumn)this.DataGrid1.Columns[0];
foreach(object index in chkColumn.UnSelectIndexes)
{
Response.Write(index.ToString()+"<br>");
}
CheckBoxColumn chkColumn = (CheckBoxColumn)this.DataGrid1.Columns[0];
foreach(object index in chkColumn.UnSelectedDataKeys)
{
Response.Write(index.ToString()+"<br>");
} - 全选/取消全选
foreach(DataGridItem item in this.DataGrid1.Items)
{
HtmlInputCheckBox chkBox=(HtmlInputCheckBox)item.FindControl("checkboxCol");
chkBox.Checked = true;
}
//如果你自定义了列控件的ID,"checkboxCol"换成自定义的ID值 - 获得选择行的任意列的
CheckBoxColumn chkColumn = (CheckBoxColumn)this.DataGrid1.Columns[0];
foreach(object index in chkColumn.SelectIndexes)
{
Response.Write(DataGrid1.Items[(int)index].Cells[1].Text);
}
基本的使用就介绍完了,都非常的简单.当然我们可以在这个列控件的基础上扩展新的功能,比如在Head加入全选/取消选择框
if(itemType == ListItemType.Header)
{
CheckBox headerCheckBox = new CheckBox();
headerCheckBox.ID = "chkAll";
headerCheckBox.CheckedChanged += new EventHandler(this.headerCheckBox_CheckedChanged);
headerCheckBox.AutoPostBack = true;
headerCheckBox.Text = "全选/取消";
cell.Controls.Add(headerCheckBox);
}
private void headerCheckBox_CheckedChanged(object sender, EventArgs e)
{
foreach (DataGridItem item in this.Owner.Items)
{
//iterate each DataGridItem and find our checkbox
HtmlInputCheckBox chkBox = (HtmlInputCheckBox) item.FindControl("checkboxCol");
//now set that checkboxCol value = to selected
if(chkBox.Checked == false)
chkBox.Checked = true;
else
chkBox.Checked = false;
}
}
{
CheckBox headerCheckBox = new CheckBox();
headerCheckBox.ID = "chkAll";
headerCheckBox.CheckedChanged += new EventHandler(this.headerCheckBox_CheckedChanged);
headerCheckBox.AutoPostBack = true;
headerCheckBox.Text = "全选/取消";
cell.Controls.Add(headerCheckBox);
}
private void headerCheckBox_CheckedChanged(object sender, EventArgs e)
{
foreach (DataGridItem item in this.Owner.Items)
{
//iterate each DataGridItem and find our checkbox
HtmlInputCheckBox chkBox = (HtmlInputCheckBox) item.FindControl("checkboxCol");
//now set that checkboxCol value = to selected
if(chkBox.Checked == false)
chkBox.Checked = true;
else
chkBox.Checked = false;
}
}