Reputation: 63
I have Datagridview and combobox. I need to send data from Datagridview to combobox (I need that for update that data and return it back to Datagridview).
I'm using this code in DoubleClick event of Datagridview to get data from datagridview to combobox and another textbox and 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
is a ComboBox , mtb_NomContrat
is a TextBox, and mdtp_DATEECHIANCE
is DateTimePicker.
Upvotes: 0
Views: 2083
Reputation: 10393
If you want to show the double-clicked cell content to the ComboBox
, you may use DataGridView.CurrentCell.Value
, and ComboBox.Items.Add()
as follows.
private void dataGridView1_DoubleClick(object sender, EventArgs e)
{
var val = dataGridView1.CurrentCell.Value;
comboBox1.Items.Add(val);
}
Doing so will only 'add' an item, but to show an item in the ComboBox
you'll need to set the SelectedIndex
as well.
To show the most-recently added item:
private void dataGridView1_DoubleClick(object sender, EventArgs e)
{
var val = dataGridView1.CurrentCell.Value;
comboBox1.Items.Add(val);
comboBox1.SelectedIndex = comboBox1.Items.Count - 1;
}
To show the first item:
private void dataGridView1_DoubleClick(object sender, EventArgs e)
{
var val = dataGridView1.CurrentCell.Value;
comboBox1.Items.Add(val);
comboBox1.SelectedIndex = 0;
}
EDIT (due to OP's updated requirements):
Let's say your DataGridView
has 3 columns, namely, ID
, Name
, and City
. And let us also say your ComboBox
is populated with those Name
values. And upon double-clicking a DataGridView
row (any cell in a particular row), you want to display in the ComboBox
the Name
value that matches the double-clicked row's Name
.
For example; DGV looks like this:
ID | Name | City
1 | Jane | New York
2 | Tom | Melbourne
3 | Chelsea | London
And your ComboBox
has values Jane
, Tom
, and Chelsea
. When you double click a row (any cell), you want to show that row's name. For instance, you double-click the cell London
and you want the ComboBox
to show Chelsea
.
In that case you need to get the current row (clicked row), then get the Name
column value in that row, and look it up in the ComboBox
values.
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;
}
Upvotes: 1