我正在使用MySQL .net连接器使用Mysqladapter
和Datagridview.Bindingsource
填充数据网格视图。这很好,但我想改变一件事:
在填充到DataGridview的表中,有一个文本类型的列。此列中的单元格在datagridview中显示为Datagridviewtextboxcell
,但我想将其更改为DataGridviewComboboxCell
(用户应在~10项之间进行选择)。
我已经尝试了很多,但没有任何效果。 DataGridview中的列是只读的,我无法将DefaultCellTemplate
更改为DataGridviewComboboxCell
,因为它不会继承DataGridviewTextboxcell
。
我也试过这个:Gridview - convert textboxcell to comboboxcell and back我认为我的问题可以通过这种方式解决,但是使用这个解决方案我还有一个问题:它没有显示DropDown按钮。
非常感谢任何帮助。
答案 0 :(得分:1)
在你联系的答案中,在行之前:
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] = cb;
尝试添加:
cb.DisplayStyle = DataGridViewComboBoxDisplayStyle.CHOOSE_ONE;
cb.FlatStyle = FlatStyle.CHOOSE_ONE;
我不确定你想要如何设计你的组合框,所以不要选择“CHOOSE_ONE”,试试风格并选择你想要的风格。
修改:好像你根本没有把它改成组合框。试试这个:
var values = new List<string> { "a", "b", "c" };
var cell = new DataGridViewComboBoxCell();
cell.DataSource = values;
dataGridView1[col, row] = cell;
答案 1 :(得分:1)
为此,您需要将新的DataGridViewComboBoxColumn添加到网格中,然后隐藏文本框列。
我使用下面的代码展示了这一点,但您可以使用设计器执行相同的操作(只需使用设计器设置我在代码中设置的属性)。
需要注意的关键事项是:
以下是添加列的代码:
// 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;
}