设置下拉列表项的默认值

因为工作需要,最近用到了DataGridViewComboBoxColumn,需要让它在DataGridView中显示时包含默认值。在网上查找过相关资料,对于我这种新手来说理解起来仍是困难,索性自己动手写了一个测试程序,若有说的不对的地方欢迎拍砖:-)。

  DataGridViewComboBoxColumn列用于在DataGridView单元格中实现具有类似ComboBox的功能,就是可以从下拉框中选择需要显示在单元格中的内容。在设置默认值的时候,有两种情况:一是DataGridView显示时已绑定了数据源;二是DataGridView显示时未绑定数据源,只是在新增行时需要显示默认值。

  第一种情况,假设DataGridView显示到界面时已绑定了数据源,我们需要设置DataGridViewComboBoxColumn列的DataPropertyName列为DataGridView绑定的数据源列的名称,部分代码如下:

DataTable dept = new DataTable();
DataColumn col = new DataColumn("dept_id", Type.GetType("System.String")) { Unique = true };//学院代码 dept.Columns.Add(col); col = new DataColumn("dept_name", Type.GetType("System.String"));//学院名称 dept.Columns.Add(col); dept.Rows.Add("001", "计算机学院"); dept.Rows.Add("002", "电气学院"); dept.Rows.Add("003", "机械学院");
 
DataGridViewComboBoxColumn cbxCol = new DataGridViewComboBoxColumn             {                 Name = "Udept",                 DataSource = dept,                 DisplayMember = "dept_name",//DataGridViewComboBoxColumn数据源中的列 ValueMember = "dept_id",                 DataPropertyName = "Udept",//注意,DataGridView数据源中的列 HeaderText = "学院", DisplayStyle = DataGridViewComboBoxDisplayStyle.DropDownButton//这里设置为DropDownButton是为了看起来更像ComboBox             };             dgv.Columns.Add(cbxCol);

可以看到DisplayMember和ValueMember属性与ComboBox中的使用是一样的,并且ValueMember与DataPropertyName值也不同(这样看起来数据源比较有层次,也可以设置为相同,不过理解起来不是特别直观),DataGridView绑定的数据源为stu,其声明如下,

DataTable stu = new DataTable(); DataColumn col = new DataColumn("Uno", Type.GetType("System.String"));//学号 stu.Columns.Add(col); col = new DataColumn("Uname", Type.GetType("System.String"));//姓名 stu.Columns.Add(col); col = new DataColumn("Udept", Type.GetType("System.String"));//院系 stu.Columns.Add(col);
stu.Rows.Add("2013001", "Jerry", "001");
stu.Rows.Add("2013002", "Tom", "002");
stu.Rows.Add("2013003", "Mike", "003");

可以看到stu表中Udept列的数据全部来源于dept表中的dept_id列。

当在Form_Load()中绑定DataGridView数据源时效果如下:

  第二种情况,DataGridView显示时未绑定数据源,只是在新增行时需要显示默认值,部分代码如下:

需要将DataGridView的AllowUserToAddRows属性设为false,为true时新增的行不能设置默认值(能力有限,还没找到办法,希望大家不吝赐教~);新建AddNewRow()方法如下,

private void AddNewRow()         {             DataRowView dr = ((DataTable)dgv.DataSource).DefaultView.AddNew();             dr["Udept"] = "001";//这里注意,DataGridView的数据源中"学院"一列对应的是Udept,千万别写成dept_id了 dr.EndEdit();         }

新增行时指定了Udept列的值为"001",那么每次点击添加新行时,"学院"一栏都是"计算机学院"了,效果如下:

需要完整源码的请留言,大家共同进步吧;-)

posted @ 2019-05-22 16:45  厦门哈韩  阅读(1258)  评论(0编辑  收藏  举报