似乎这是个比较常用的功能,不过还是第一次作,没有想到什么更好的方法,我是用一个前台的临时表实现的.
测试用的数据库为SqlServer ,默认的Northwind数据库,Customers表.
新建一个窗体,加入一个DataGrid,先取表中所有数据,放到数据集dsCustomer里面.
然后建立一个临时表dtCustomer,拷贝dsCustomer里面存放数据的表的副本到dtCustomer.加入选择字段dcSelected(DataColumn类),遍历一次dtCustomer里面的记录,给dcSelected字段赋值.
建立表格样式,字段样式当然要根据dtCustomer的结构来定义了,并映射到表dtCustomer,然后绑定就可以.
使dcSelected列可以修改,只要在DataGrid的单击事件中加入代码就可以了.
具体需要的代码如下:
1.创建绑定时需要的临时数据表.
private DataTable dtTemp = null;
![](/Images/OutliningIndicators/None.gif)
private void CreateTempTable(DataSet dsInit, string tableName)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
if (dsInit != null && dsInit.Tables[0] != null)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
dtTemp = dataSet11.Tables[0].Copy();
DataColumn dc = new DataColumn("IsSelected", typeof(bool));
dtTemp.Columns.Add(dc);
foreach(DataRow dr in dtTemp.Rows)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
dr["IsSelected"] = true;
}
}
dtTemp.TableName = tableName;
}
2.设置DataGrid的样式(这里面的列就按照需要的自己定义好了,前提是必须包含在你所创建的临时数据表中)
private void SetDataGridTyle(string tableName)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
DataGridTableStyle tableStyle = new DataGridTableStyle();
tableStyle.MappingName = tableName;
DataGridBoolColumn dgbcSelected = new DataGridBoolColumn();
dgbcSelected.HeaderText = "IsSelected";
dgbcSelected.MappingName = "IsSelected";
tableStyle.GridColumnStyles.Add(dgbcSelected);
![](/Images/OutliningIndicators/InBlock.gif)
DataGridTextBoxColumn dgtbcCity = new DataGridTextBoxColumn();
dgtbcCity.HeaderText = "Cityy" ;
dgtbcCity.MappingName = "City";
tableStyle.GridColumnStyles.Add(dgtbcCity);
this.dataGrid1.TableStyles.Clear();
this.dataGrid1.TableStyles.Add(tableStype);
}
3.允许单击修改选择列
private void dataGrid1_Click(object sender, System.EventArgs e)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
if (dataGrid1.CurrentCell.ColumnNumber == 0)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
bool s = false;
if (dtTemp.DefaultView[dataGrid1.CurrentRowIndex]["IsSelected"] == DBNull.Value)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
s = true;
}
else
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
s = bool.Parse(dtTemp.DefaultView[dataGrid1.CurrentRowIndex]["IsSelected"].ToString());
}
dtTemp.DefaultView[dataGrid1.CurrentRowIndex]["IsSelected"] = !s;
dataGrid1.Refresh();
}
}
通过上述操作,我们就可以在不影响显示的情况下,根据行记录前面的CheckBox来选择我们需要的数据.
后面又补充了在列标题加入CheckBox实现全选功能,不过有些牵强...
http://snowlove67.cnblogs.com/archive/2005/12/20/300910.html