Reputation: 79685
I need to handle when a cell is double-clicked in a ReadOnly DataGrid (not DataGridView unfortunately), but the MouseDoubleClick event is not being fired. How can I make the event fire?
I'm creating the DataGrid and subscribing to the event:
var table = new DataTable();
table.Columns.Add("foo");
table.Rows.Add(new object[] { "foo" });
table.Rows.Add(new object[] { "foo" });
dataGrid1.DataSource = table;
dataGrid1.MouseDoubleClick += DataGrid1_MouseDoubleClick;
dataGrid1.ReadOnly = true;
The event is only if I double click on the border between cells. When I click on a cell a ReadOnly textbox appears which seems to eat the second click event:
I found an old thread in Experts Exchange, where they say as much:
Well, not only is the double click event not being captured when clicking on a cell, it is not being caught by the datagrid message queue. I inherited a datagrid and overrode the wndproc, checking to see if I could detect the double click. It captures the click message, but no WM_LBUTTONDBLCLK message comes through. I suspect that MS has the child cell control (see DataGridColumnStyle class and derivatives) hook the grid control and prevent the message from even continuing to the grid. Trying to pre-hook that child or the grid could have pretty messy results, so I am avoiding that.
I don't really need the TextBox control so if there is a way to suppress the cells from "activating" or showing it, that would be a good enough solution for me as well.
Note: I know DataGrid is obsolete, but I'm dealing with legacy code, please don't comment to tell me to use DataGridView - it doesn't help me.
Upvotes: 3
Views: 2573
Reputation: 125302
When a mouse down occurs on a cell, the TextBox
editing control gets the focus and receives other mouse ups and downs, so double click event of DataGrid will not raise.
Since your DataGrid
is read-only, you can change DataGridTextBoxColumn to not show editing control. This way double click event will raise. To do so, it's enough to override this overload of Edit
method and do nothing:
public class MyDataGridTextBoxColumn : DataGridTextBoxColumn
{
protected override void Edit(CurrencyManager source, int rowNum,
Rectangle bounds, bool readOnly, string displayText, bool cellIsVisible)
{
}
}
Example
private void Form1_Load(object sender, EventArgs e)
{
var dt = new DataTable();
dt.Columns.Add("A");
dt.Columns.Add("B");
dt.Rows.Add("1", "11");
dt.Rows.Add("2", "22");
var dg = new DataGrid();
dg.Dock = DockStyle.Fill;
this.Controls.Add(dg);
dg.BringToFront();
dg.DataSource = dt;
var ts = new DataGridTableStyle();
ts.GridColumnStyles.Add(new MyDataGridTextBoxColumn() { MappingName = "A" });
ts.GridColumnStyles.Add(new MyDataGridTextBoxColumn() { MappingName = "B" });
dg.TableStyles.Add(ts);
dg.DoubleClick += dg_DoubleClick;
}
void dg_DoubleClick(object sender, EventArgs e)
{
MessageBox.Show("DoubleClick!");
}
Upvotes: 1