简体   繁体   中英

dataGridView - change column to combobox

I do my dataGridViews by this code

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";

What i want, is change Column 4 and 7 to a Combobox, with data from another table in my database.

How is that possible=

Try something like this:

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);

Just use DataPropertyName instead of ValueMember

From this answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM