How to disable the ability to select in a DataGridView?

C#.NetWinformsDatagridview

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

I'd go with this:

private void myDataGridView_SelectionChanged(Object sender, EventArgs e)
{
    dgvSomeDataGridView.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.

Solution 2 - C#

You may set a transparent background color for the selected cells as following:

DataGridView.RowsDefaultCellStyle.SelectionBackColor = System.Drawing.Color.Transparent;

Solution 3 - C#

Enabled property to false

or

this.dataGridView1.DefaultCellStyle.SelectionBackColor = this.dataGridView1.DefaultCellStyle.BackColor;
this.dataGridView1.DefaultCellStyle.SelectionForeColor = this.dataGridView1.DefaultCellStyle.ForeColor;

Solution 4 - C#

I fixed this by setting the Enabled property to false.

Solution 5 - C#

If you don't need to use the information in the selected cell then clearing selection works but if you need to still use the information in the selected cell you can do this to make it appear there is no selection and the back color will still be visible.

private void dataGridView_SelectionChanged(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in dataGridView.SelectedRows)
        {
            dataGridView.RowsDefaultCellStyle.SelectionBackColor = row.DefaultCellStyle.BackColor;
        }
    }

Solution 6 - C#

This worked for me like a charm:

row.DataGridView.Enabled = false;

row.DefaultCellStyle.BackColor = Color.LightGray;

row.DefaultCellStyle.ForeColor = Color.DarkGray;

(where row = DataGridView.NewRow(appropriate overloads);)

Solution 7 - C#

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);

Solution 8 - C#

I liked user4101525's answer best in theory but it doesn't actually work. Selection is not an overlay so you see whatever is under the control

Ramgy Borja's answer doesn't deal with the fact that default style is not actually a color at all so applying it doesn't help. This handles the default style and works if applying your own colors (which may be what edhubbell refers to as nasty results)

dgv.RowsDefaultCellStyle.SelectionBackColor = dgv.RowsDefaultCellStyle.BackColor.IsEmpty ? System.Drawing.Color.White : dgv.RowsDefaultCellStyle.BackColor;
dgv.RowsDefaultCellStyle.SelectionForeColor = dgv.RowsDefaultCellStyle.ForeColor.IsEmpty ? System.Drawing.Color.Black : dgv.RowsDefaultCellStyle.ForeColor;

Solution 9 - C#

you have to create a custom DataGridView

`

namespace System.Windows.Forms
{
    class MyDataGridView : DataGridView
    {
        public bool PreventUserClick = false;

        public MyDataGridView()
        {
       
        }
        protected override void OnMouseDown(MouseEventArgs e)
        {
            if (PreventUserClick) return;
        
            base.OnMouseDown(e);
        }
    }
}

` note that you have to first compile the program once with the added class, before you can use the new control.

then go to The .Designer.cs and change the old DataGridView to the new one without having to mess up you previous code.

private System.Windows.Forms.DataGridView dgv; // found close to the bottom

private void InitializeComponent() {
    ...
    this.dgv = new System.Windows.Forms.DataGridView();
    ...
}

to (respective)

private System.Windows.Forms.MyDataGridView dgv;

this.dgv = new System.Windows.Forms.MyDataGridView();

Solution 10 - C#

Its in VB, but shouldnt be difficult to translate to C#: If you want to lock datagridview, use dg.ReadOnly == True;

If you want to prevent user from selecting another row, just remember old selection and based on condition set or not set the row which shall be selected. Assuming, that multiselection is turned off:

    Private Sub dg_SelectionChanged(sender As Object, e As EventArgs) Handles dg.SelectionChanged
    Static OldSelection As Integer
      If dg.Rows.Count > 0 Then
          If dg.SelectedRows(0).Index <> OldSelection And YOURCONDITION Then
            dg.Rows(OldSelection).Selected = True
          End If

        OldSelection = dg.SelectedRows(0).Index
      End If
    End Sub

Solution 11 - C#

Here's what has always worked for me to disable the default selection in a class inherited from DataGridView:

// REQUIRES: SelectionMode = DataGridViewSelectionMode.FullRowSelect
protected override void SetSelectedRowCore(int rowIndex, bool selected)
{		
	base.SetSelectedRowCore(rowIndex, selected && ALLOW_DEFAULT_SELECTION);
}
bool ALLOW_DEFAULT_SELECTION = false;

Usually the goal is to disable it entirely (in order to implement our own custom selection and drawing process). When the goal is to allow the default selection only at specific times the boolean can be wrapped like so:

public void SelectRowExplicitly(int index, bool selected = true)
{
	try
	{
		ALLOW_DEFAULT_SELECTION = true;
		Rows[index].Selected = selected;
	}
	finally
	{
		ALLOW_DEFAULT_SELECTION = false;
	}
}

Solution 12 - C#

Use the DataGridView.ReadOnly property

The code in the MSDN example illustrates the use of this property in a DataGridView control intended primarily for display. In this example, the visual appearance of the control is customized in several ways and the control is configured for limited interactivity.

Observe these settings in the sample code:

// Set property values appropriate for read-only
// display and limited interactivity
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AllowUserToDeleteRows = false;
dataGridView1.AllowUserToOrderColumns = true;
dataGridView1.ReadOnly = true;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.MultiSelect = false;
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
dataGridView1.AllowUserToResizeColumns = false;
dataGridView1.ColumnHeadersHeightSizeMode = 
DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
dataGridView1.AllowUserToResizeRows = false;
dataGridView1.RowHeadersWidthSizeMode = 
DataGridViewRowHeadersWidthSizeMode.DisableResizing;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMahdi TahsildariView Question on Stackoverflow
Solution 1 - C#edhubbellView Answer on Stackoverflow
Solution 2 - C#user4101525View Answer on Stackoverflow
Solution 3 - C#Ramgy BorjaView Answer on Stackoverflow
Solution 4 - C#RickView Answer on Stackoverflow
Solution 5 - C#PWCoderView Answer on Stackoverflow
Solution 6 - C#PaddyView Answer on Stackoverflow
Solution 7 - C#SharpCView Answer on Stackoverflow
Solution 8 - C#BengineerView Answer on Stackoverflow
Solution 9 - C#Jannik SvenssonView Answer on Stackoverflow
Solution 10 - C#WernerView Answer on Stackoverflow
Solution 11 - C#IVSoftwareView Answer on Stackoverflow
Solution 12 - C#Angshuman AgarwalView Answer on Stackoverflow