Home > Back-end >  Why we cannot delete datagridview columns with delete key in C# on default?
Why we cannot delete datagridview columns with delete key in C# on default?

Time:01-25

I am creating columns dynamically at runtime. I can delete rows with delete key but I cannot delete columns. Every method I find involves deleting column by column id or column name. In order to do that, I have to find the column name somehow when its selected and then store it somewhere and then write code to delete. My question is why we cannot just delete columns like rows.? Is there any simpler solution to my problem (selecting a column and delete it with key) ? and yes I have gone through almost every post/question before coming here.

CodePudding user response:

Well… a possible “crude” yet simple solution is to delete the column if the user clicks on a column header cell. Obviously this is not really a good idea considering most users would expect the grid to sort by that column when the header is clicked and we would still want them to be able to do this. So.. possibly add the requirement that the user must hold the “Ctrl” Key AND click on the column header to delete the column.

However, I would think you need some mechanism to restore (undelete) all the previously removed columns. In that case, we could require the user to press BOTH the “Ctrl” Key and the “Alt” Key to restore all the columns from the original data source. If you are not using a data source then to restore the grid, you may need to re-fill the whole grid manually. Also it should be noted that if the user removes ALL the columns using the “Ctrl” click, then the user will never be able to get the columns back as there will be NO column header cells to click. Possibly always leave at least one column displayed.

You could put this code in the grids ColumnHeaderMouseClick Event and it may look something like…

private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
  if (Control.ModifierKeys.HasFlag(Keys.Control) && Control.ModifierKeys.HasFlag(Keys.Alt)) {
    dataGridView1.DataSource = null;
    dataGridView1.DataSource = YourGridsDataSource;  // or re-fill the grid if it has no data source
    return;
  }
  if (dataGridView1.ColumnCount == 1) {
    return;
  }
  if (Control.ModifierKeys.HasFlag(Keys.Control)) {
    dataGridView1.Columns.Remove(dataGridView1.Columns[e.ColumnIndex].Name);
  }
}
  •  Tags:  
  • Related