Datagridview removes all columns

Is it possible to delete all columns from a datagrid in one delete?

I know that I could loop and delete them one by one, or delete it all and create it.

But you can just clear the columns and leave the grid in place so that users can start a new job. that is, return it to its original state.

Ok here is the code i have

private void PopulateGrid() { UserVGrid.AutoGenerateColumns = false; UserVGrid.Columns.Clear(); List<string> _values = populate.GetVaribles; foreach (var line in _values) { if (!line.Contains("Startind")) { string[] newline = line.Split('='); DataGridViewColumn newColumn = new DataGridViewTextBoxColumn(); newColumn.Name = newline[0]; newColumn.HeaderText = newline[1]; newColumn.ToolTipText = newline[2]; UserVGrid.Columns.Add(newColumn); } } 

so suppose _ values โ€‹โ€‹have the value apple, pear as values

runs this method once, and I get a datagrid with two columns named apple and pear.

run it a second time this time with _values โ€‹โ€‹containg char, table.
And I ended up with 4 columns of apple, pear, chair and table. What I want, the second time it starts, clears the fist of the grid, and then applies the new columns.

Greetings

Aaron

+4
source share
4 answers

The DataGridView column collection has a Clear () method.

 dataGridView1.Columns.Clear(); 

This does not work with datagridview bound and auto-generated columns - in this case, just replace the data source with a zero or empty data source:

 dataGridView1.DataSource = null; 

or turn off auto-generation and create columns in the code:

 dataGridView1.AutoGenerateColumns = false; DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn(); dataGridView1.Columns.Add(col); 

These manually created columns will be deleted using the Clear () method.

+20
source

Here's what worked for me

  List<string> lstOverride = new List<string>(); lstOverride.Add("IssuerOnly"); lstOverride.Add("TickerOnly"); lstOverride.Add("All"); lstOverride.Add("Private Equity"); lstOverride.Add("Ignore"); DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn(); cmb.HeaderText = "Override"; cmb.Name = "cmb"; cmb.DataSource = lstOverride; cmb.DataPropertyName = "Override"; dgvWebData.Columns.Add(cmb); 

I added a DataGridViewComboBoxColumn and set DataPropertyName for it in the column in which I needed to release.

0
source

Clear data

 If ds.Tables.Count > 0 Then ds.Tables(0).Columns.Clear() ds.Tables(0).Rows.Clear() End If 

and set the datagridview data source to nothing

 dg.DataSource = Nothing 
0
source

to delete dataGridView columns you can do this: "P_Comment" is the name of the column

  dataGridView1.Columns.Remove("p_Comment"); 

and to delete all columns you can use

 dataGridView1.Columns.Clear(); 
0
source

All Articles