[英]how to pass value from Datagridview to combobox in c#?
我有Datagridview和combobox 。 我需要将数据从Datagridview发送到组合框 (我需要更新数据并将其返回给Datagridview)。
我在Datagridview的DoubleClick事件中使用以下代码,将数据从datagridview获取到组合框和另一个文本框和DateTimepicker:
private void mgrid_searchClient_Contrat_DoubleClick(object sender, EventArgs e)
{
mcb_NomClient.Text= this.mgrid_searchClient_Contrat.CurrentRow.Cells[0].Value.ToString();
mtb_NomContrat.Text = this.mgrid_searchClient_Contrat.CurrentRow.Cells[1].Value.ToString();
mdtp_DATEECHIANCE.Text = this.mgrid_searchClient_Contrat.CurrentRow.Cells[2].Value.ToString();
}
mcb_NomClient
是ComboBox, mtb_NomContrat
是TextBox, mdtp_DATEECHIANCE
是DateTimePicker。
如果要将双击的单元格内容显示到ComboBox
,则可以如下使用DataGridView.CurrentCell.Value
和ComboBox.Items.Add()
。
private void dataGridView1_DoubleClick(object sender, EventArgs e)
{
var val = dataGridView1.CurrentCell.Value;
comboBox1.Items.Add(val);
}
这样做只会“添加”一个项目,但是要在ComboBox
显示一个项目,您还需要设置SelectedIndex
。
要显示最近添加的项目:
private void dataGridView1_DoubleClick(object sender, EventArgs e)
{
var val = dataGridView1.CurrentCell.Value;
comboBox1.Items.Add(val);
comboBox1.SelectedIndex = comboBox1.Items.Count - 1;
}
要显示第一项:
private void dataGridView1_DoubleClick(object sender, EventArgs e)
{
var val = dataGridView1.CurrentCell.Value;
comboBox1.Items.Add(val);
comboBox1.SelectedIndex = 0;
}
编辑(由于OP的更新要求):
假设您的DataGridView
有3列,即ID
, Name
和City
。 让我们也说您的ComboBox
填充了这些Name
值。 双击DataGridView
行(特定行中的任何单元格)后,您想要在ComboBox
显示与双击行的Name
相匹配的Name
值。
例如; DGV看起来像这样:
ID | 姓名| 市
1 | 简| 纽约
2 | 汤姆| 墨尔本
3 | 切尔西| 伦敦
而且您的ComboBox
值包括Jane
, Tom
和Chelsea
。 当您双击一行(任何单元格)时,您想要显示该行的名称。 例如,双击London
单元格,并希望ComboBox
显示Chelsea
。
在这种情况下,您需要获取当前行(单击的行),然后获取该行中的“ Name
列值,然后在ComboBox
值中查找它。
private void dataGridView1_DoubleClick(object sender, EventArgs e)
{
var currentRow = dataGridView1.CurrentRow;
var selectedName = currentRow.Cells[1].Value;
var index = comboBox1.Items.IndexOf(selectedName.ToString());
comboBox1.SelectedIndex = index;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.