Is it possible in a single hit to remove all columns from a datagrid?
I know I could loop though and remove them one by one, or remove the whole thing and create it.
But it is possible to simply clear columns and leave the grid in place so users can start fresh. i.e. put it back 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 lets assume _values has apple, pear as values
running this method once and i get a datagrid with two colums named apple and pear.
running it a second time this time with _values containg char , table.
And i end up with 4 colums apple, pear, chair and table. What I want is the second time it is run it clears the grid fist and then applied the new colums.
Cheers
Aaron
The DataGridView
columns collection has a Clear() method.
dataGridView1.Columns.Clear();
This doesn't work with a bound datagridview and autogenerated columns - in that case simply replace the datasource with null or with an empty datasource:
dataGridView1.DataSource = null;
or turn off autogeneration and create the columns in code:
dataGridView1.AutoGenerateColumns = false;
DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
dataGridView1.Columns.Add(col);
These manually generated columns will be removed by the Clear() method.