数据网格视图 数据库中的数据填充,其中一个单元格是组合框 c#
本文关键字:数据 一个 单元格 组合 视图 网格 数据网 数据库 填充 | 更新日期: 2023-09-27 18:32:56
我有一个数据网格视图,我需要用数据库中的内容填充它。我的数据库内容位于通常如下所示的数据表中:
产品编号 产品名称版本
1ABC 1.1
1ABC 2.1
1ABC 3.1
2 定义 3.1
2定义 3.2
3 吉希 1.1
4 JKL 1.1
4 JKL 1.2
现在我的问题是,当我在数据网格视图中显示内容时,我希望它这样显示,其中版本应该是一个下拉组合框单元格,因此每个产品都有一个版本列表:
产品编号 产品名称版本
1ABC 1.1
2.1
3.1
2 定义 3.1
3.2
3 吉希 1.1
4 JKL 1.1
1.2
请帮助我实现这一目标。我不能直接说:
dataGridView1.DataSource = getdatatable((
所以请不要建议这样做,因为它给了我一个没有组合框的平面视图。热切期待得到肯定的答复。是否可以在数据网格视图中绘制每一行,并使用产品可用的所有版本填充该行中的组合框?请帮忙。蒂亚
本质上,您需要对查询的数据进行排序,将每个唯一产品及其所有版本的列表保存下来。 然后,您将手动为 DataGridView 创建列,我将在下面介绍。
为了模拟这个场景,我创建了以下对象类:
// The type of binding object for your dgview source.
public class Product
{
public Product()
{
this.Version = new List<double>();
}
public int ID { get; set; }
public string Name { get; set; }
public List<double> Version { get; set; }
}
在返回所有对象的查询中,我会做这样的事情:
public BindingList<Product> YourQueryCall()
{
BindingList<Product> products = new BindingList<Product>();
/*
* Your code to query the db.
*/
while reader.Read()
{
Product existingProduct = new Product();
int id = // value from the reader
string name = // value from the reader
double version = // value from the reader
try
{
existingProduct = products.Single(p => p.ID == id && p.Name == name);
existingProduct.Version.Add(version);
}
catch // No product yet exists for this id and name.
{
existingProduct.ID = id;
existingProduct.Name = name;
existingProduct.Version.Add(version);
products.Add(existingProduct);
}
}
return products;
}
这将仅存储唯一的产品及其版本列表。 在窗体中,要在 ComboBoxColumn 中显示每一行的唯一版本列表,请执行以下操作:
public Form1()
{
InitializeComponent();
this.Products = YourQueryCall();
this.FillDGView();
}
public BindingList<Product> Products { get; set; }
public void FillDGView()
{
DataGridViewTextBoxColumn col1 = new DataGridViewTextBoxColumn();
col1.Name = "Product ID";
col1.ValueType = typeof(int);
dataGridView1.Columns.Add(col1);
DataGridViewTextBoxColumn col2 = new DataGridViewTextBoxColumn();
col2.Name = "Product Name";
col2.ValueType = typeof(string);
dataGridView1.Columns.Add(col2);
DataGridViewComboBoxColumn col3 = new DataGridViewComboBoxColumn();
col3.Name = "Version";
col3.ValueType = typeof(double);
dataGridView1.Columns.Add(col3);
for (int i = 0; i < this.Products.Count; i++)
{
DataGridViewRow row = (DataGridViewRow)(dataGridView1.Rows[0].Clone());
DataGridViewTextBoxCell textCell = (DataGridViewTextBoxCell)(row.Cells[0]);
textCell.ValueType = typeof(int);
textCell.Value = this.Products[i].ID;
textCell = (DataGridViewTextBoxCell)(row.Cells[1]);
textCell.ValueType = typeof(string);
textCell.Value = this.Products[i].Name;
DataGridViewComboBoxCell comboCell = (DataGridViewComboBoxCell)(row.Cells[2]);
comboCell.ValueType = typeof(double);
comboCell.DataSource = this.Products[i].Version;
comboCell.Value = this.Products[i].Version[0];
dataGridView1.Rows.Add(row);
}
}
希望这有帮助!