C#用Combobox替换DataGridView中的默认文本框

我仍然是C#的新手,但我正在开发一个从Access数据库中提取数据的WinForms应用程序。 我目前正在处理一个表单,该表单使用DataAdapter和DataSet动态地将表中的内容加载到DataGridView中。

到目前为止,表单正在按预期工作。 目前,要添加新记录,您必须在一行中的每个单元格中键入数据。 我想要做的是用combobox替换几列(文本框)。 换句话说,不是手动输入数据,而是使用下拉combobox并从列表中选择条目。 我还想从SQL生成combobox数据成员但是如果这太多了,我可以手动编写每个项目的代码。

我可以在运行时向datagridview添加一个combobox,但这不是我想要做的。 由于列是在运行时通过代码创建的,我不知道如何修改该方法后面的列。

因此,例如,我想用“R”,“PG-13”,“PG”等组合成员替换“Rating”的文本框单元格。

public partial class frmBulkInsert : Form { OleDbConnection conn; OleDbDataAdapter da; DataSet ds; OleDbCommandBuilder cmdbl; public frmBulkInsert() { InitializeComponent(); } private void frmBulkInsert_Load_1(object sender, EventArgs e) { // Load all records from the table into the datagridview. try { dataConnectionSettings(); } catch (Exception ex) { MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void button1_Click(object sender, EventArgs e) { this.Close(); } private void ConnectToDatabase() { conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\ronniejones.JONES\Documents\Access Projects\Movie_2013.mdb"; } private void btnUpdateRecords_Click(object sender, EventArgs e) { try { //DataSet changes = (ds).GetChanges(); cmdbl = new OleDbCommandBuilder(da); //da.Update(ds, "Movie_2013"); int numRows = da.Update(ds, "Movie_2013"); MessageBox.Show(numRows + " Record(s) Updated", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void dataConnectionSettings() { //DataGridViewComboBoxColumn cboColumn; conn = new OleDbConnection(); ConnectToDatabase(); conn.Open(); da = new OleDbDataAdapter("SELECT ID, Title, [Minutes], Rating, Category, Format, Actor1, Actor2, Actor3, Actor4, [Status] FROM [Movies] ORDER BY ID", conn); ds = new DataSet(); da.Fill(ds, "Movie_2013"); dataGridView1.DataSource = ds.Tables[0]; 

创建列后,您无法更改其类型。 您可以通过两种方式实现目标。

  1. 如您所述,创建所需的列,将其添加到网格并绑定数据。 如果设置了列的DataPropertyName属性,那么在绑定数据时,数据列将绑定到网格列。 DataGridView将自动生成其他列。 将第二个数据源绑定到combobox本身。

  2. 修改数据库,使列表由数据库提供,绑定将自动创建组合列。

你可能想做这样的事情:

将数据源分配给gridview后,该数据源是来自查询的表:

  DataGridViewComboBoxCell ComboBoxCell1 = new DataGridViewComboBoxCell(); ComboBoxCell1.Items.AddRange(new string[] { "aaa", "bbb", "ccc" }); this.dataGridView1[0, 2] = ComboBoxCell1; DataGridViewComboBoxCell ComboBoxCell2 = new DataGridViewComboBoxCell(); ComboBoxCell2.Items.AddRange(new string[] { "aaa", "bbb", "ccc" }); this.dataGridView1[1, 2] = ComboBoxCell2; DataGridViewComboBoxCell ComboBoxCell3 = new DataGridViewComboBoxCell(); ComboBoxCell3.Items.AddRange(new string[] { "aaa", "bbb", "ccc" }); this.dataGridView1[2, 2] = ComboBoxCell3; 

其中this.dataGridView1[int, int]是网格的[column,row],因此您可以计算数据表有多少行, dt.Rows.Count + 1将是[column,Row]中的Row值]

希望这是你正在寻找的,这有帮助