简体   繁体   中英

C# WinForms DataGridView - Constant Row Selected!

I have a winforms datagridview that seems to always have at least one row selected all the time. I'm not interested in being able to select the rows at all really, I just need the user to be able to select the checkbox in column 1. Any ideas why there is always at least 1 row selected? How can i prevent this? Will it affect the ability to select the checkbox in column1?

Below are my Datagridview settings:

this.dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
this.dataGridView1.DefaultCellStyle.ForeColor = Color.Black;
this.dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
this.dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
this.dataGridView1.MultiSelect = false;
this.dataGridView1.RowHeadersVisible = false;
this.dataGridView1.RowsDefaultCellStyle.BackColor = Color.WhiteSmoke;
this.dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.LightGray;
this.dataGridView1.ColumnCount = 0;

colSelect = new DataGridViewCheckBoxColumn();
colSelect.HeaderText = "Select Message";
colSelect.Width = 90;
this.dataGridView1.Columns.Insert(0, colSelect);
this.dataGridView1.Columns[0].DataPropertyName = "msgSelect";

Goober, I encountered a similar problem, where I needed user to select rows using checkboxes. The first row is always selected by default after the gridview is populated irrespective of the gridview settings. To make sure the first row is not selected, everytime the gridview is populated, do a ClearSelection():

this.dgridvw.DataSource = this.MyTable;
this.dgridvw.ClearSelection();

ClearSelection() clears all the selected rows.

You should use DataGridView.ClearSelection() to remove any selection(s) after you have populated your DataGridView.

Also you can make specific columns read only allow which would allow to restrict editing to your checkbox column only. See DataGridViewColumn.ReadOnly Property

Make sure your are NOT calling the method to load the data from the form constructor. If you call it from the form.load()

also after the datagridview is loaded do this

DataGridView.Rows[0].Selected = false;

Select the datagridview. Then, in the properties window scroll down until you find the property SelectionMode and change it to FullColumnSelect.

Alternatively if you want them to just select one checkbox at a time change it to CellSelect

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM