如何在数据网格视图单元格中添加两行
本文关键字:添加 两行 单元格 数据 数据网 视图 网格 | 更新日期: 2023-09-27 18:34:53
在这里,我试图在一个单元格中添加多行,但失败了。
请帮助我编码,并告诉我是否有其他控件可以这样做。
string[] innerrow1 = new string[] { "50", "60", "70" };
string[] innerrow2 = new string[] { "a", "b", "c" };
dataGridView1.ColumnCount = 3;
dataGridView1.Columns[0].Name = "Product ID";
dataGridView1.Columns[1].Name = "Product Name";
dataGridView1.Columns[2].Name = "Product Price";
dataGridView1.Rows.Insert(0, innerrow2);
object[] row = new object[] { "1", innerrow1, "1000" };
dataGridView1.Rows.Add(row);
row = new object[] { "2", innerrow2, "2000" };
dataGridView1.Rows.Add(row);
如果您希望所有 tring 都包含在单个单元格中,只需更改代码,如下所示
string innerrow1 = "50 60 70";
string innerrow2 = "a b c";
如果你想要一个组合框
string[] innerrow1 = new string[] { "50", "60", "70" };
string[] innerrow2 = new string[] { "a", "b", "c" };
DataGridViewTextBoxColumn Col1 = new DataGridViewTextBoxColumn();
Col1.HeaderText = "Product ID";
dataGridView1.Columns.Add(Col1);
DataGridViewComboBoxColumn Col2 = new DataGridViewComboBoxColumn();
Col2.HeaderText = "Product Name";
Col2.Name = "Product Name";
Col2.MaxDropDownItems = 3;
Col2.Items.Add(innerrow1[0]);
Col2.Items.Add(innerrow1[1]);
Col2.Items.Add(innerrow1[2]);
dataGridView1.Columns.Add(Col2);
DataGridViewTextBoxColumn Col3 = new DataGridViewTextBoxColumn();
Col3.HeaderText = "Product Price";
dataGridView1.Columns.Add(Col3);
dataGridView1.Rows.Add(new object[] { "1", innerrow1[0], "1000" });
dataGridView1.Rows.Add(new object[] { "2", innerrow1[1], "2000" });
dataGridView1.Rows.Add(new object[] { "3", innerrow1[2], "3000" });
如果要为每行提供不同的下拉列表
public Form1()
{
InitializeComponent();
string[] innerrow1 = new string[] { "50", "60", "70" };
string[] innerrow2 = new string[] { "a", "b", "c" };
DataGridViewTextBoxColumn Col1 = new DataGridViewTextBoxColumn();
Col1.HeaderText = "Product ID";
dataGridView1.Columns.Add(Col1);
DataGridViewComboBoxColumn Col2 = new DataGridViewComboBoxColumn();
Col2.HeaderText = "Product Name";
Col2.Name = "Product Name";
Col2.MaxDropDownItems = 3;
Col2.Items.Add(innerrow1[0]);
Col2.Items.Add(innerrow1[1]);
Col2.Items.Add(innerrow1[2]);
dataGridView1.Columns.Add(Col2);
DataGridViewTextBoxColumn Col3 = new DataGridViewTextBoxColumn();
Col3.HeaderText = "Product Price";
dataGridView1.Columns.Add(Col3);
dataGridView1.Rows.Add(new object[] { "1", innerrow1[0], "1000" });
dataGridView1.Rows.Add(new object[] { "2", innerrow2[0], "2000" });
setCellComboBoxItems(dataGridView1, 0, 1, innerrow1);
setCellComboBoxItems(dataGridView1, 1, 1, innerrow2);
}
private void setCellComboBoxItems(DataGridView dataGrid, int rowIndex, int colIndex, object[] itemsToAdd)
{
DataGridViewComboBoxCell dgvcbc = (DataGridViewComboBoxCell)dataGrid.Rows[rowIndex].Cells[colIndex];
// You might pass a boolean to determine whether to clear or not.
dgvcbc.Items.Clear();
foreach (object itemToAdd in itemsToAdd)
{
dgvcbc.Items.Add(itemToAdd);
}
}