Csharp/C#教程:在绑定的DataGridView中将DataGridViewColumn更改为DataGridViewComboBoxColumn分享


在绑定的DataGridView中将DataGridViewColumn更改为DataGridViewComboBoxColumn

我有一个绑定到DataTable的DataGridView,我使用SQLiteDataAdapter来更新一个SQLite数据库。 我正在尝试将其中一个列设为DataGridViewComboBoxColumn,但尽管我可以在其上放置项并更改其单元格值,但我无法通过DataAdapter更新它。

加载DataGridView后我正在这样做:

DataGridViewComboBoxColumn cbCol = new DataGridViewComboBoxColumn(); dataGridView1.Columns.Insert(2, cbCol); dataGridView1.Columns[2].HeaderText = dataGridView1.Columns[3].HeaderText; dataGridView1.Columns[3].Visible = false; string[] cbList = new[] {"item1","item2"}; foreach (string str in cbList) { cbCol.Items.Add(str); } for (int i = 0 ; i<= dataGridView1.Rows.Count - 1; i++) { dataGridView1.Rows[i].Cells[2].Value = dataGridView1.Rows[i].Cells[3].Value; } 

问题是ComboBoxColumn没有绑定到DataTable,我必须在运行DataAdapter.Update之前检查更改并修改隐藏列。

有什么方法可以避免这种情况吗? 完美的场景将是这样的:

  private void dataGridView1_ColumnAdded(object sender, DataGridViewColumnEventArgs e) { if (columnadded.headertext == "xxx") { //Then this is column is the same but in a ComboBox format. //The ComboBoxColumn, when added, must show the same values and have //the same binding as if if was the regular column. } } 

创建DataGridViewComboBoxColum ,将其添加到网格并绑定数据。 如果将列的DataPropertyName属性设置为db列id,那么在绑定数据时,该数据列将绑定到您的网格列。 DataGridView将自动生成其他列(如果设置AutoGenerateColumns=true )。 将第二个数据源绑定到combobox本身。

 DataGridViewComboBoxColumn col1 = new DataGridViewComboBoxColumn (); col1.Name = //name of the column col1.HeaderText = //header text of the column col1.DataPropertyName = //db column id col1.DataSource = // datasource for combo dataGridView1.Columns.Add(col1); dataGridView1.AutoGenerateColumns = true; dataGridView1.DataSource = // your datasource 

我刚才有类似的问题,我不得不补充一下

 col1.DisplayMember = "number"; //column name in source table for col1 

以上解决方案,然后它工作。

上述就是C#学习教程:在绑定的DataGridView中将DataGridViewColumn更改为DataGridViewComboBoxColumn分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/956439.html

(0)
上一篇 2021年11月20日
下一篇 2021年11月20日

精彩推荐