c#中datagridview怎么设置将combobox放进去
发布网友
发布时间:2022-10-10 21:10
我来回答
共2个回答
热心网友
时间:2023-10-09 12:50
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)语句,直接报错
热心网友
时间:2023-10-09 12:51
在 FormLoad 事件中 DataGridView1.Controls.Add(ComboBox1);
在 DataGridView 的CurrentCellChanged事件中
private void dg1_CurrentCellChanged(object sender, EventArgs e)
{ DataGridViewCell CurrnetCell = dg1.CurrentCell;
if(CurrnetCell!=null && CurrnetCell.OwningColumn.Name=="第三列")
{
....sql返回dataset
ComboBox1.Visible = true;
ComboBox1.DataSource = tableNameCombox.DefaultView;
ComboBox1.DisplayMember = "ColumnName";
ComboBox1.ValueMember = "Num";
System.Drawing.Rectangle TmpRect = dg1.GetCellDisplayRectangle(CurrnetCell.ColumnIndex, CurrnetCell.RowIndex, true);
ComboBox1.Size = TmpRect.Size;
ComboBox1.Top = TmpRect.Top;
ComboBox1.Left = TmpRect.Left;
}追问抄也要看题目抄啊 ~~我要的都没这么复杂