[英]Set ComboBox in Specific Cell in DataGridView
我已经在DataGridView行/列中看到了关于combobox的多个线程,但是没有什么真正集中在一个单元格上的。 我正在尝试遍历DataGridView中的所有单元格,当它识别出应该具有选项On / Off的Parameter时,它将在其中加载ComboBox。
我一直在努力的代码是:
dataGridView1.DataSource = typeof(Parameter);
dataGridView1.DataSource = _paramList;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell ce in row.Cells)
{
foreach (Information i in _information)
{
if (ce.Value.ToString() == "Light")
{
DataGridViewComboBoxCell c = new DataGridViewComboBoxCell();
c.Items.Add("On");
c.Items.Add("Off");
dataGridView1.Rows[ce.RowIndex].Cells[ce.ColumnIndex] = c;
}
}
}
}
它将引发错误“集合已被修改;枚举操作可能无法执行”。 我猜这与它用组合框填充单元格并尝试继续foreach语句有关吗? 有任何想法/更改可以解决此问题?
谢谢!
Foreach循环为您处理枚举器,它们很容易得到此错误(枚举无法继续,集合已修改)。 您可以使用for循环解决此问题。 我测试了以下内容(首先尝试过foreach-没有骰子),我们似乎还不错。
还要注意-在设置新项目之前,我必须将实际单元格值设置为null。 没有这个,我得到一个错误“ datagridcomboboxcell的值无效”(或类似的东西)。
包括我所有的复制测试代码:
using System;
using System.Data;
using System.Windows.Forms;
namespace WindowsFormsApp5
{
public partial class Form1 : Form
{
private DataGridView oDg;
public Form1()
{
InitializeComponent();
CreateGrid();
this.Shown += Form1_Shown;
}
private void Form1_Shown(object sender, EventArgs e)
{
TestIt();
}
private void TestIt()
{
//works
for (int i = 0;i < oDg.RowCount; i++)
{
for (int j = 0;j< oDg.ColumnCount; j++)
{
oDg.Rows[i].Cells[j].Value = null; //this is important.
DataGridViewComboBoxCell c = new DataGridViewComboBoxCell();
c.Items.Add("On");
c.Items.Add("Off");
oDg.Rows[i].Cells[j] = c;
}
}
//does not work
//foreach (DataGridViewRow row in oDg.Rows)
//{
// foreach (DataGridViewCell ce in row.Cells)
// {
// oDg.Rows[ce.RowIndex].Cells[ce.ColumnIndex].Value = null;
// DataGridViewComboBoxCell c = new DataGridViewComboBoxCell();
// c.Items.Add("On");
// c.Items.Add("Off");
// oDg.Rows[ce.RowIndex].Cells[ce.ColumnIndex] = c;
// }
//}
}
private void CreateGrid()
{
oDg = new DataGridView();
oDg.Width = 800;
oDg.Height = 800;
oDg.DataSource = CreateDataSource();
this.Controls.Add(oDg);
}
private DataTable CreateDataSource()
{
DataTable oDt = new DataTable();
for(int i = 0; i < 8; i++)
{
DataColumn col = new DataColumn(i.ToString(),typeof (String));
oDt.Columns.Add(col);
}
for (int i = 0; i < 99; i++)
{
DataRow rw = oDt.NewRow();
for (int j = 0;j < oDt.Columns.Count; j++)
{
rw[j] = j.ToString();
}
oDt.Rows.Add(rw);
}
return oDt;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.