向DataGridView动态添加组合框/文本框
本文关键字:文本 组合 添加 DataGridView 动态 | 更新日期: 2023-09-27 18:10:52
我不是很有经验的工作与Windows窗体。我有一定的要求,那就是我想添加行到DataGridView和列有组合框或文本框。有没有人请指导我如何将"控制"列添加到DataGridView行。基本上,我应该能够用控件添加尽可能多的行。组合框也是级联的。
谢谢。
你能做的:
- 添加一个组合框列
- 为每行 更改此列的值
你不能做的事:
- 为多个行设置不同的columntype
这意味着:
您不能为每一行决定应该使用哪种类型的列。当你需要一个特定行的组合框时,你不能将它添加到包含所有只需要textbox列的行的datagridview中。
你可以做的是:
运行时,有一个成员函数叫做DataGridView.GetCellDisplayRectangle。使用此方法,您可以在运行时获得特定单元格的边界。假设组合框只应用于这一行。方案如下:
void OnSelectionChanged(Object sender, ChangedEventArgs e){
if(DataGridView1.CurrentCell.RowIndex == 4){
// Show one single ComboBox in the specified Cell in the Row 4 (actually Row 3 because RowIndex is zero-based)
if(this.Controls.Contains(ComboBox1))
this.Controls.Remove(ComboBox1);
ComboBox ComboBox1 = gcnew ComboBox();
// Define the properties of your combobox:
ComboBox1.Text = "Choose an Option...";
ComboBox1.AutoSize = false; // Important, because you will change the size programmatically
// ...
// Get the boundaries of the desired cell
Rectangle CellBounds = DataGridView1.GetCellDisplayRectangle(
/*ColumnIndex*/ 1,
/*RowIndex*/ DataGridView1.CurrentCell.RowIndex,
/*CutOverflow*/ false);
// By applying size and location to the combobox you make sure it is displayed on the cell
ComboBox1.Size = CellBounds.Size;
ComboBox1.Location = CellBounds.Location;
// Add the ComboBox to your Controls in order to get it rendered when your window is shown
this.Controls.Add(ComboBox1);
}
现在您的组合框显示在您在GetCellDisplayRectangle( ColumnIndex, RowIndex, CutOverflow)
指定的单元格上。当然,这段代码可以进一步优化,因为每次选择另一个单元格时,都会创建一个新的组合框并将其添加到控件容器中。在多次选择之后,这可能会使用大量内存。