I wonder if you can give me a push in the right direction - I have some C# code and have two DataGridViews ()dgv1 and dgv2). When a button is pressed, the dataGridViews are filled (by way of a Datatable as the source) from two different databases. Both DataGridViews have the same number of columns and I am using column 4 (cell 3) to check if a row in dgv1 has the same value in cell 3 as any of the rows in dgv2. What I am trying to achieve is;
- if a row is selected in dgv1 and there is a matching row (same value in cell 3), then the row is automatically highlighted in dgv2
- when the selection is changed in dgv1, the same happens i.e. the foreach loop checks dgv2 to find a match
- if a selected row in dgv1 does not have a match in dgv2, I want to display a messagebox stating "no match"
Now, I wrote the code in the SelectionChanged event of the dgv1 and the foreach is working fine, and does exactly what I want....until I put an else condition. When I put the else condition, the message box is displayed each time a selection is made in dgv1, even if there IS a match. What I need is for the message box to only appear if there is no match between dgv1 and dgv2. Below is my code;
private void dgv1_SelectionChanged(object sender, EventArgs e)
{
this.dgv2.ClearSelection();
this.dgv2.Tag = "";
txtBxID.Text = "";
foreach (DataGridViewRow dgv2row in dgv2.Rows)
{
if (dgv1.CurrentRow.Cells[3].Value.ToString() == Convert.ToString(dgv2row.Cells[3].Value))
{
dgv2.Selected = true;
txtBxID.Text = dgv2.Cells[6].Value.ToString();
dgv2.Tag = dgv2row.Cells[6].Value.ToString();
MessageBox.Show(Convert.ToString(dgv2.Tag));
}
else
{
MessageBox.Show("no match");
}
}
}
I hope this all makes sense, and a thousand apologies if this same or similar question has been asked. I am still trying to familiarise myself with StackOverflow.
EDIT: following the two answers by @KlausGütter and @KostandinVllahu, I have attempted to add a Boolean variable as shown below. This has solved half the problem, though. What happens now is - when the button is clicked (to fill the dataGridViews) the message box showing "no match" is displayed repeatedly about 5 times (presumably for each row to be added to the dataGridViews, that is 5 in this case), and once I've clicked OK on the message boxes and they've disappeared, the code does what I want it. Where am I going wrong with the Boolean? Have I misplaced it? I have done the below;
private void dgv1_SelectionChanged(object sender, EventArgs e)
{
this.dgv2.ClearSelection();
this.dgv2.Tag = "";
txtBxID.Text = "";
Boolean match = false;
foreach (DataGridViewRow dgv2row in dgv2.Rows)
{
if (dgv1.CurrentRow.Cells[3].Value.ToString() == Convert.ToString(dgv2row.Cells[3].Value))
{
match = true;
dgv2.Selected = true;
txtBxID.Text = dgv2.Cells[6].Value.ToString();
dgv2.Tag = dgv2row.Cells[6].Value.ToString();
MessageBox.Show(Convert.ToString(dgv2.Tag));
}
}
if (!match)
{
MessageBox.Show("no match");
}
}
Many Thanks in Advance.