我正在动态地将行和列添加到数据表中。这些行添加到我能看到的范围,但是一旦我运行代码,就不会出现任何内容。一旦foreach循环结束,它就像是在刷新表格吗?菜鸟问题。抱歉。
summaryTable.Columns.Add("StationName", typeof(string));
summaryTable.Columns.Add("DepartmentCode", typeof(string));
var row = summaryTable.NewRow();
foreach (var item in issuesByClass)
{
row.SetField("StationName", item.StationName);
row.SetField("DepartmentCode", item.DepartmentCode);
foreach (var itemClass in item.Lookup)
{
if (!itemClassLookup.ContainsKey(itemClass.Key)) continue;
var itemClassValue = itemClassLookup[itemClass.Key];
// Ensure column hasn't been added before
if (!summaryTable.Columns.Contains(itemClassValue))
{
summaryTable.Columns.Add(itemClassValue, typeof(decimal));
}
row.SetField(itemClassValue, itemClass.Sum());
}
if (!summaryTable.Columns.Contains("GrandTotal"))
{
summaryTable.Columns.Add("GrandTotal", typeof(decimal));
}
row.SetField("GrandTotal", item.GrandTotal);
}
return summaryTable;
小窗口形成应用示例:
public Form1()
{
this.InitializeComponent();
this.Test();
}
public void Test()
{
var dt = new DataTable();
var subs = new[] { "Sub 1", "Sub 2", "Sub 3" };
var row = dt.NewRow();
foreach (var sub in subs)
{
if (!dt.Columns.Contains("Subs"))
{
dt.Columns.Add("Subs");
}
row.SetField("Subs", sub);
}
dt.Columns.Add("Test");
row.SetField("Test", 1M);
this.dataGridView1.DataSource = dt;
}