限制DataGridView c#中的输入
Restricting the input in DataGridView c#
所以我在表单中有一个 DataGridView,我想限制向其单元格添加数据。
我正在尝试将任何添加行的单元格设为组合框,这样用户就必须从组合框中为单元格选择数据。
此外,当用户向最后一行添加任何值时,dataGridView 将自动创建一个新行,并且这个新行将作为组合框添加。
这张照片显示了我的 table,我知道每一列的预期值,这就是为什么我想在每个单元格中使用组合框来限制它。
创建列时,将它们分别创建为 DataGridViewComboBoxColumn
。正如您所说:
[You] know the expected values for each column
因此,您可以通过这种方式创建列,并绑定每列的源代码。例如:
public Form1()
{
InitializeComponent();
List<List<string>> options = new List<List<string>>()
{
new List<string>() { "Foo 1", "Foo 2", "Foo 3" },
new List<string>() { "Bar 1", "Bar 2", "Bar 3" },
new List<string>() { "Baz 1", "Baz 2", "Baz 3" }
};
List<string> names = new List<string>() { "Foo", "Bar", "Baz" };
for (int i = 0; i < names.Count; i++)
{
DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
col.Name = names[i];
col.DataSource = options[i];
this.dataGridView1.Columns.Add(col);
}
}
所以我在表单中有一个 DataGridView,我想限制向其单元格添加数据。
我正在尝试将任何添加行的单元格设为组合框,这样用户就必须从组合框中为单元格选择数据。
此外,当用户向最后一行添加任何值时,dataGridView 将自动创建一个新行,并且这个新行将作为组合框添加。
这张照片显示了我的 table,我知道每一列的预期值,这就是为什么我想在每个单元格中使用组合框来限制它。
创建列时,将它们分别创建为 DataGridViewComboBoxColumn
。正如您所说:
[You] know the expected values for each column
因此,您可以通过这种方式创建列,并绑定每列的源代码。例如:
public Form1()
{
InitializeComponent();
List<List<string>> options = new List<List<string>>()
{
new List<string>() { "Foo 1", "Foo 2", "Foo 3" },
new List<string>() { "Bar 1", "Bar 2", "Bar 3" },
new List<string>() { "Baz 1", "Baz 2", "Baz 3" }
};
List<string> names = new List<string>() { "Foo", "Bar", "Baz" };
for (int i = 0; i < names.Count; i++)
{
DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
col.Name = names[i];
col.DataSource = options[i];
this.dataGridView1.Columns.Add(col);
}
}