dataGridView - 将列更改为组合框

时间:2016-02-21 19:03:59

标签: c# datagridview combobox

我通过此代码

执行dataGridViews
sda = new SqlDataAdapter("SELECT id, acc_name, acc1_company, acc1_no, acc1_type, acc2_company, acc2_no, acc2_type FROM accounting", con);
                dt = new DataTable();
                sda.Fill(dt);

                dataGridView1.DataSource = dt;
                dataGridView1.Columns[0].Visible = false;
                dataGridView1.Columns[1].HeaderText = "Name";
                dataGridView1.Columns[2].HeaderText = "Company 1";
                dataGridView1.Columns[3].HeaderText = "Accounts 1";
                dataGridView1.Columns[4].HeaderText = "Type 1";
                dataGridView1.Columns[5].HeaderText = "Company 2";
                dataGridView1.Columns[6].HeaderText = "Accounts 2";
                dataGridView1.Columns[7].HeaderText = "Type 2";

我想要的是将第4列和第7列更改为Combobox,并使用我数据库中另一个表中的数据。

怎么可能=

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

dataGridView1.AutoGenerateColumns = false;

DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(String));
dt.Columns.Add("Money", typeof(String));
dt.Rows.Add(new object[] { "Hi", 100 });
dt.Rows.Add(new object[] { "Ki", 30 });

DataGridViewComboBoxColumn money = new DataGridViewComboBoxColumn();
var list11 = new List<string>() { "10", "30", "80", "100" };
money.DataSource = list11;
money.HeaderText = "Money";
money.DataPropertyName = "Money";

DataGridViewTextBoxColumn name = new DataGridViewTextBoxColumn();
name.HeaderText = "Name";
name.DataPropertyName = "Name";

dataGridView1.DataSource = dt;
dataGridView1.Columns.AddRange(name, money);

只需使用DataPropertyName代替ValueMember

来自this answer