本質上,您需要對您查詢的數據進行排序,使用所有版本的列表保存每個獨特的產品。然後,您將手動創建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);
}
}
希望這有助於!