DataGridViewComboBoxColumn pCombo; private void Teaching_Add_Load(object sender, EventArgs e) { MyDBase DB = new MyDBase(DBUser.sserver,DBUser.DBName, DBUser.suser, DBUser.spasswd); DataSet DS= DB.GetRecordset("select * from view_teach_tmp"); dataGridView1.DataSource = DS.Tables[0]; pCombo = new DataGridViewComboBoxColumn(); SqlDataReader RD = DB.DBDataReader("select * from expert"); while (RD.Read()) { string st = RD[0].ToString().Trim() + "." + RD[1].ToString().Trim(); pCombo.Items.Add(st); } RD.Close(); dataGridView1.Columns.Add(pCombo); dataGridView1.Columns[7].HeaderText = "请选择专家"; DB.DBClose(); }
说明:
1.dataGridView中添加comboBox控件利用初始化现成的类DataGridViewComboBoxColumn,本例先把从view_teach_tmp中读出的数据加到dataGridView1中,然后把初始化的comboBox控件pCombo加到最后一列,并给标题HeaderText命名。
2.pCombo控件中显示的是expert表中的“编码.专家姓名”,若要获取编码,可用下面的函数GetENo。
string GetENo(string st) { int n, i; string s = ""; n = st.Length; for (i = 0; i < n; i++) { if (st.Substring(i, 1) == ".") return s; s = s + st.Substring(i, 1); } return "-1"; }
3.调用函数GetENo:
string ENo;
for (int i = 0; i < n; i++) { if (dataGridView1.Rows[i].Cells[7].Value == null) { MessageBox.Show("请选择专家", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } ENo = dataGridView1.Rows[i].Cells[7].Value.ToString(); ENo = GetENo(ENo); }
特别说明:
要判断pCombo控件是否全都选值,要使用if (dataGridView1.Rows[i].Cells[7].Value == null),起初使用if (dataGridView1.Rows[i].Cells[7].Value.Tostring().Trim().Length==0)语句,直接报错,打死都找不出问题所在。
时间: 2024-12-09 23:01:43