[英]how to show combobox in datagridview?
// Create and populate DataTable
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Brand", typeof(string));
// Populate it here
// With this once we set datasource of dgv, it will not generate columns automatically
dataGridView1.AutoGenerateColumns = false;
DataGridViewTextBoxColumn idCol = new DataGridViewTextBoxColumn()
{
Name = "Id",
HeaderText = "Id",
DataPropertyName = "Id",
Width = 50,
HeaderCell = new DataGridViewColumnHeaderCell()
{
Value = "Id"
}
};
DataGridViewTextBoxColumn nameCol = new DataGridViewTextBoxColumn()
{
Name = "Name",
HeaderText = "Name",
DataPropertyName = "Name",
Width = 200,
HeaderCell = new DataGridViewColumnHeaderCell()
{
Value = "Name"
}
};
DataGridViewComboBoxColumn brandCol = new DataGridViewComboBoxColumn()
{
Name = "Brand",
HeaderText = "Brand",
DataPropertyName = "Brand",
Width = 100,
HeaderCell = new DataGridViewColumnHeaderCell()
{
Value = "Brand"
},
DataSource = new List<Tuple<int, string>>() {
new Tuple<int, string>(1, "Brand 1"),
new Tuple<int, string>(2, "Brand 2"),
new Tuple<int, string>(3, "Brand 3")
},
DisplayMember = "Item2",
ValueMember = "Item1"
};
// Now we add these columns to our dgv
dataGridView1.Columns.Add(idCol);
dataGridView1.Columns.Add(nameCol);
dataGridView1.Columns.Add(brandCol);
// and at last, we bind our data to it
dataGridView1.DataSource = dt;
您可以看到我們的ComboBox
列使用與普通組合框相同的綁定系統。 為此,我使用元組列表來填充它,但您通常會從數據庫中加載該部分的數據。
假設您有這樣的 Brand 類:
public class Brand
{
public int ID { get; set; } // important to be property, not variable
public string Name { get; set; }
}
您從數據庫加載數據並創建這些對象的列表:
// I have done it manually
List<Brand> brandsList = new List<Brand>();
brandsList.Add(new Brand() { ID = 1, Name = "Brand 1 });
brandsList.Add(new Brand() { ID = 2, Name = "Brand 2 });
brandsList.Add(new Brand() { ID = 3, Name = "Brand 3 });
然后,您將上部組合框列定義更改為:
DataGridViewComboBoxColumn brandCol = new DataGridViewComboBoxColumn()
{
Name = "Brand",
HeaderText = "Brand",
DataPropertyName = "Brand",
Width = 100,
HeaderCell = new DataGridViewColumnHeaderCell()
{
Value = "Brand"
},
DataSource = brandsList,
DisplayMember = "Name",
ValueMember = "ID"
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.