Reputation: 33
I am trying to get an event where if you left click a cell in a DataGridView
, the contents of that cell will go into a Textbox
. The same goes if you right click a cell in a DataGridView
the contents will go into a different Textbox
. Here is the code I have so far
private void dataGridView2_mirror_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
switch (MouseButtons)
{
case MouseButtons.Left:
textBox3.Text = dataGridView2_mirror.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
break;
case MouseButtons.Right:
textBox4.Text = dataGridView2_mirror.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
break;
}
}
The problem that I am getting is that it is not recognizing that the cell is being clicked, where as if I put the code into a regular MouseEventArgs
for mouse down the code will recognize whether it is a right click or a left click.
Upvotes: 0
Views: 3247
Reputation: 11
I came up with this idea below. Also i think it's better to use CellMouseUp or CellMouseDown event.
private void dataGridView2_mirror_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button.HasFlag(MouseButtons.Left))
{
textBox3.Text = dataGridView2_mirror.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
return;
}
if (e.Button.HasFlag(MouseButtons.Right))
{
textBox4.Text = dataGridView2_mirror.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
return;
}
}
Upvotes: 1
Reputation: 54433
You are not testing the current button value but the enumeration itself which is the same as if (1 == 1)
.. ((Or to be precise: None == some integer
))
The minumum fix would be to change to
switch (e.Button)
But: The MouseButtons are a flag enumeration, which means more than one value can be true. Get into the habit of testing just the flag you actually want and always test them like this:
e.Button.HasFlag(MouseButtons.Left)..
This makes using a switch
hard but, as so often and with only two buttons to discern switch
makes little sense anyway..
Upvotes: 0