您的位置:首页 > 编程语言 > ASP

怎样让WinForms下DataGrid可以像ASP.NET下的DataGrid一样使用自定义的模板列

2010-02-07 12:26 525 查看
被问到一个问题:怎么把WinForms里的DataGrid的绑定了数据库bit字段的列默认显示的CheckBox换成“男”和“女”,也就是 说怎么样像ASP.NET的模板列那样可以自定义。(此处不考虑在SQL在用Case把数据结果转换了)
由于,基本没有搞过WinForms,所 以这个问题弄了很久才搞掂,可能对于WinForms高手来说,这是一个很简单的问题。(我搜了一下网页,没有找到直接的解决方案,问了一些搞过 WinForms的朋友,也没有直接的解决方案,所以把我的解决方案放在博客园首页,DUDU如觉不适合,请移除。)解决这个问题的副作用就是对 WinForms的机制有了一点了解。

最终实现效果:
//用Label显示"男"和"女",并且点击一次变成相反的
class DataGridCustomBoolColumnStyle : DataGridColumnStyle
//使用方法
DataGridTableStyle dgts = new DataGridTableStyle();
dgts.MappingName = this.dataSet11.Employees.TableName;
this.dataGrid1.TableStyles.Add(dgts);

GridColumnStylesCollection gcsc = dataGrid1.TableStyles[0].GridColumnStyles;

DataGridBoolColumn dgbc = gcsc[gcsc.Count - 1] as DataGridBoolColumn;

DataGridCustomBoolColumnStyle dgcbc = new DataGridCustomBoolColumnStyle();
dgcbc.MappingName = dgbc.MappingName;
gcsc.Remove(dgbc);
gcsc.Add(dgcbc);
this.employeesTableAdapter.Fill(this.dataSet11.Employees);
this.dataGrid1.DataSource = this.dataSet11.Employees; 这个实现很简单,数据与显示之间的映射是固定的,既然简单的能实现,我们再来实现个复杂的,用ComboBox来表示一些固定值的选择,比如 enum和bool,因为数据库中的数据并没有enum,所以,这个DataGridComboBoxColumnStyle提供两个委托,可以数据到 ComboBox项和ComboBox项到数据之间做一个处理

//可以灵活适应各种情况的ComboBox列样式
public delegate string FormatValueToString(object value);
public delegate object ParseStringToValue(string value);
class DataGridComboBoxColumnStyle:DataGridColumnStyle
//使用方法
DataGridTableStyle dgts = new DataGridTableStyle();
dgts.MappingName = this.dataSet11.Employees.TableName;
this.dataGrid1.TableStyles.Add(dgts);

GridColumnStylesCollection gcsc = dataGrid1.TableStyles[0].GridColumnStyles;

DataGridBoolColumn dgbc = gcsc[gcsc.Count - 1] as DataGridBoolColumn;

DataGridComboBoxColumnStyle dgcbc = new DataGridComboBoxColumnStyle();
dgcbc.MappingName = dgbc.MappingName;
//这里定义ComboBOx的样式和项,因为整个ComboBox都公开了,所以随你怎 么设置都行
dgcbc.InnerComboBox.Items.Add("男");
dgcbc.InnerComboBox.Items.Add("女");
dgcbc.InnerComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
//这里定义数据和ComboBOx项之间如何转换
dgcbc.ParseDelegate = new ParseStringToValue(ParseStringToBool);
dgcbc.FormartDelegate = new FormatValueToString(FormatBoolToString);

gcsc.Remove(dgbc);
gcsc.Add(dgcbc);
this.employeesTableAdapter.Fill(this.dataSet11.Employees);
this.dataGrid1.DataSource = this.dataSet11.Employees;

熟悉WinForms的设计思路之后,我们又可以像用ASP.NET的DataGird一样用DataGrid了。
WinForms 我是新手,请多指教。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: