1
votes

So I have a DataGridView in a form, and I want to restrict adding data to its cell.

I'm trying to make the cells of any added row a combobox, so that the user will have to choose the data for the cell from the combobox.

Also when a user adds any value to the last row, the dataGridView will automatically create a new row, and this new row will be added as combo boxes.

This pic shows my table, I know the expected values for each column, thats why I want to restrict it with comboboxes in each cell.

first pic

1

1 Answers

1
votes

When you create the columns, create them each as a DataGridViewComboBoxColumn. As you stated:

[You] know the expected values for each column

Therefore you can create the columns this way with each column's source bound. For example:

public Form1()
{
  InitializeComponent();

  List<List<string>> options = new List<List<string>>()
  {
    new List<string>() { "Foo 1", "Foo 2", "Foo 3" },
    new List<string>() { "Bar 1", "Bar 2", "Bar 3" },
    new List<string>() { "Baz 1", "Baz 2", "Baz 3" }
  };

  List<string> names = new List<string>() { "Foo", "Bar", "Baz" };

  for (int i = 0; i < names.Count; i++)
  {
    DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
    col.Name = names[i];
    col.DataSource = options[i];
    this.dataGridView1.Columns.Add(col);
  } 
}

Choosing from column("Foo")Choosing from column("Bar")Choosing from column("Baz")