将DataGridView中的列转换为ComboBox [英] Converting Column in DataGridView into a ComboBox

查看:84
本文介绍了将DataGridView中的列转换为ComboBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用C#编写的WinForms应用程序,其中有一个绑定到从SQL数据库填充的数据源的DataGridView.

I have a WinForms application written in C# in which I have a DataGridView bound to a DataSource populated from a SQL Database.

我的代码如下-

string sqlText = "SELECT columns FROM table;";
SqlCommand sqlCom = new SqlCommand(sqlText);
DataTable table = new DataTable();
SqlConnection linkToDB = DatabaseConnection();
sqlCom.Connection = linkToDB;
linkToDB.Open();
using (linkToDB)
using (SqlDataAdapter adapter = new SqlDataAdapter(sqlCom))
{
    adapter.Fill(table);
}     
dataMyGridView.DataSource = table;

我试图如下添加一个DataGridViewComboBox-

I have tried to add a DataGridViewComboBox to this as follows -

DataGridViewComboBoxColumn colBox = new DataGridViewComboBoxColumn();
colBox.DataSource = GetListOfValues();   
dataMyGridView.Columns.Add(colbox);

现在可以使用,但是它会在ComboBox中添加一个全新的列,而不是将现有列之一转换为ComboBox.

Now this works, but it adds an entirely new column with the ComboBox, rather than converting one of the existing columns into a ComboBox.

谁能解释我如何将dataMyGridView中的现有列转换为ComboBox?

Can anyone explain how I convert an existing Column in the dataMyGridView into a ComboBox?

GetListOfValues函数仅返回一个DataTable,其中包含ComboBox字段的所有可能值.它可以正确填充,但是就像我说的那样,它是一本全新的专栏.如何将添加的ComboBox引用到表"中的相关属性.

The GetListOfValues function simply returns a DataTable containing all the possible values for the ComboBox field. It populates correctly, but like I said, its an entirely new column. How do I refer the added ComboBox to the relevant property in 'table'.

推荐答案

我回答了类似的创建列后,您将无法更改其类型.您可以通过两种方式实现目标.

Once a column is created you can't change its type. You can achieve your goal in two ways.

1.创建所需的列,将其添加到网格并绑定数据.如果设置列的 DataPropertyName 属性,则当绑定数据时,该数据列将被绑定到网格列.DataGridView将自动生成其他列.将第二个数据源绑定到combobox列本身.

1.Create the required column, add it to the grid and bind the data. If you set the DataPropertyName property of your column then when your data is bound that data column will get bound to your grid column. The DataGridView will generate other columns automatically. Bind a second datasource to the comboboxcolumn itself.

2.修改数据库,使列表由数据库提供,并且绑定将自动创建comboboxcolumn.

2.Modify your database such that the list is provided by the database and binding will automatically create comboboxcolumn.

这篇关于将DataGridView中的列转换为ComboBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆