1.在DataGridView中添加一个隐藏列,用来与数据源字段绑定:隐藏列.DataPropertyName = 数据源.列名;
2. 用一个DataTable建立实际值和显示值的映射:
DataTable dtRelation = new DataTable();
dtRelation.Columns.Add("Code",typeof(byte));
dtRelation.Columns.Add("DisplayString",typeof(string));
dtRelation.Rows.Add(new object[] { 0, "苹果" });
dtRelation.Rows.Add(new object[] { 1, "香蕉" });
dtRelation.Rows.Add(new object[] { 2, "西瓜" });
3.设置下拉列表列(DataGridViewComboxColumn)属性:
下拉列表列.DataSource = dtRelation;
下拉列表列.ValueMember = "Code";
下拉列表列.DisplayMember = "DisplayString";
4.好了,接下来就是用事件函数实现两列之间的连接:
private void dgvGroupRule_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
DataGridViewComboBoxCell selCell = (DataGridViewComboBoxCell)dgvGroupRule.Rows[e.RowIndex].Cells["下拉列表列"];
selCell.Value= dgvGroupRule.Rows[e.RowIndex].Cells["隐藏列"].Value;
}
private void dgvGroupRule_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (dgvGroupRule.Columns[e.ColumnIndex].Name.Equals("下拉列表列"))
{
DataGridViewComboBoxCell selCell = (DataGridViewComboBoxCell)dgvGroupRule.Rows[e.RowIndex].Cells["下拉列表列"];
dgvGroupRule.Rows[e.RowIndex].Cells["隐藏列"].Value = selCell.Value;
}
}
最后隐藏列Value属性的变化影响与DataGridView绑定的数据源,SqlDataAdapter直接根据该数据源进行相应的数据库表操作,不需关心DataGridView的列值。
一调试果然通过了。但是后来一想又不对,为什么要使用一项隐藏列呢?原来最初查资料的时候看到有人的解决方法只简单的一行“使用隐藏列”,感觉似乎还真需要用隐藏列来跟数据源字段绑定。唉,有了这种想法先入为主,就老是想到用隐藏列。其实不用这么复杂:
1. 在构造函数里用一个DataTable建立实际值和显示值的映射:
DataTable dtRelation = new DataTable();
dtRelation.Columns.Add("Code",typeof(byte));
dtRelation.Columns.Add("DisplayString",typeof(string));
dtRelation.Rows.Add(new object[] { 0, "苹果" });
dtRelation.Rows.Add(new object[] { 1, "香蕉" });
dtRelation.Rows.Add(new object[] { 2, "西瓜" });
2.设置下拉列表列(DataGridViewComboxColumn)属性:
下拉列表列.DataSource = dtRelation;
下拉列表列.ValueMember = "Code";
下拉列表列.DisplayMember = "DisplayString";
下拉列表列.DataPropertyName = 数据源.列名;