設置DataGridViewComboBoxColumn列的默認值


  因為工作需要,最近用到了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",那么每次點擊添加新行時,"學院"一欄都是"計算機學院"了,效果如下:

需要完整源碼的請留言,大家共同進步吧;-)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM