Tearsdontfalls
Tearsdontfalls

Reputation: 777

Change Textboxcell to a Comboboxcell at run time

I'm using MySQL .net connector to fill a Datagridview using Mysqladapter and Datagridview.Bindingsource. That works good, but I want to change one thing:

In the table which is filled to the DataGridview, there is a column with a text type. The cells in this columns are displayed as a Datagridviewtextboxcell in the datagridview, but I want to change it to DataGridviewComboboxCell (the users should select between ~10 items).

I already tried a lot but nothing worked as it should. The Columns in the DataGridview are readonly, I cannot change DefaultCellTemplate to a DataGridviewComboboxCell, cause it doesn't inherit DataGridviewTextboxcell.

I also tried this: Gridview - convert textboxcell to comboboxcell and back and I think my problem could be solved over this way, but with this solution I have also 1 problem: It doesnt show a DropDown Button.

Any help will be greatly appreciated.

Upvotes: 0

Views: 3036

Answers (2)

svinja
svinja

Reputation: 5576

In the answer you linked, before the line:

dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] = cb;

Try adding:

cb.DisplayStyle = DataGridViewComboBoxDisplayStyle.CHOOSE_ONE;
cb.FlatStyle = FlatStyle.CHOOSE_ONE;

I am not sure how exactly you want to style your comboboxes, so instead of "CHOOSE_ONE", try out the styles and pick the style you want.

Edit: Seems like you're not changing it to a combobox at all. Try this:

var values = new List<string> { "a", "b", "c" };
var cell = new DataGridViewComboBoxCell();
cell.DataSource = values;
dataGridView1[col, row] = cell;

Upvotes: 1

David Hall
David Hall

Reputation: 33163

To do this you need to add a new DataGridViewComboBoxColumn to the grid and then hide the text box column.

I show this using code below but you can do the same using the designer (just set the properties I set in code using the designer).

The key things to note are:

  • DataPropertyName refers to a property of the grid's data source - likely your text box source
  • You need to provide the column with its own data source
  • DisplayMember and ValueMember refer to the data source of the column

Here is the code to add the column:

// Here I do this in the form constructor - there are other places you can do it
public Form1()
{
    InitializeComponent();

    DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();

    // You need to set some properties on the column to make it work

    // Datasource is the source (usually a list) of objects to show in the combobox
    col.DataSource = dataSource;

    col.DataPropertyName = "ColumnInGridDataSource";
    col.DisplayMember = "DisplayProperty";
    col.ValueMember = "ValueProperty";

    dataGridView1.Columns.Add(col);

    // This hides the textboxcolumn
    dataGridView1.Columns["YourTextBoxColumnName"].Visible = false;
}

Upvotes: 1

Related Questions