Alex Rivera | Logout

How to disable the ability to select in a DataGridView?

Asked 2012-07-04T13:32:50.560
72

I want to use my DataGridView only to show things, and I want the user not to be able to select any row, field or anything from the DataGridView.

How can I do this?

Edit
Report

2 Answers

150

I'd go with this:

private void myDataGridView_SelectionChanged(Object sender, EventArgs e)
{
     myDataGridView.ClearSelection();  
}

I don't agree with the broad assertion that no DataGridView should be unselectable. Some UIs are built for tools or touchsreens, and allowing a selection misleads the user to think that selecting will actually get them somewhere.

Setting ReadOnly = true on the control has no impact on whether a cell or row can be selected. And there are visual and functional downsides to setting Enabled = false.

Another option is to set the control selected colors to be exactly what the non-selected colors are, but if you happen to be manipulating the back color of the cell, then this method yields some nasty results as well.

answered 2012-12-19T15:29:00.893
1

I found setting all AllowUser... properties to false, ReadOnly to true, RowHeadersVisible to false, ScollBars to None, then faking the prevention of selection worked best for me. Not setting Enabled to false still allows the user to copy the data from the grid.

The following code also cleans up the look when you want a simple display grid (assuming rows are the same height):

int width = 0;
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
    width += dataGridView1.Columns[i].Width;
}

dataGridView1.Width = width;
dataGridView1.Height = dataGridView1.Rows[0].Height*(dataGridView1.Rows.Count+1);
answered 2013-05-29T16:12:58.873

Your Answer