How do I select a value in a DataGridViewComboBoxCell?

前端 未结 1 1410
南笙
南笙 2021-02-08 23:30

I have DataGridViewComboBoxCell and a DataTable. The data in Table I bound with DataGridViewComboBoxCell using DataSource and set ValueMember, and DisplayMember.



        
1条回答
  •  抹茶落季
    2021-02-09 00:05

    Instead of adding a cell to your grid add a DataGridViewComboBox column.

    DataGridViewComboBoxColumn c = new DataGridViewComboBoxColumn();
    c.Name = "ComboColumn";
    c.DataSource = dataTable;
    c.ValueMember = "ID";
    c.DisplayMember = "Item";
    dataGridView1.Columns.Add(c);
    

    To select a particular value you set the Value property of a given cell.

    dataGridView1.Rows[rowIndexYouWant].Cells["ComboColumn"].Value = 1;
    
    • Note that the type here is important! In comments you say you get a System.FormatException. This can be caused by setting the wrong type to the value.

      When you set the value to 1 you are assigning an int - if for some reason you have strings in the ID column you will get the System.FormatException exception you are seeing.

      If the types differ you need to either update the DataTable definition or set the value to a string:

      dataGridView1.Rows[rowIndexYouWant].Cells["ComboColumn"].Value = "1";
      
    • Also note that this value must be present in the ID column of the DataTable that you have set as the source of the grid.

    It is usually easiest to work with a DataGridView when it has its DataSource set. In this case you can bind the ComboBoxColumn to the grid's DataSource using the DataPropertyName property.

    c.DataPropertyName = "GridDataSourceColumnName";
    

    This allows the columns value to be taken from the grid data source and for changes to the column to directly change that data source.


    Lastly, do not use the CellFormatting event here - this event is not intended for this sort of use. It is usually best to do this sort of work in the DataBindingComplete event (if you only want it done once) or during some event like DefaultValues needed or RowValidating.

    By using CellFormatting you will probably make it impossible for users to manually edit the combo box.

    0 讨论(0)
提交回复
热议问题