我在C#Winforms应用程序中使用Datagridview,每次用户从对话框/表单中保存内容时都会对其进行修改。
由于此datagridview中的行数很大,因此添加或删除会占用大量时间,并且由于datagridview是UI的一部分,因此只能在Mainform中修改它,这会使UI无法响应。
所以我现在使用的方法是传递Datatable来设置为grid的数据源。
问题是:
这是一些代码
private void FillDataGrid(Hashtable ht, bool isToModify)
{
if (ht != null && ht.Count > 0)
{
// Obtain a blank datatable with format of datagridview
DataTable tableToPass = GetFormatDataTable();
foreach (string key in ht.Keys)
{
List<myClass> values = ht[key] as List<myClass>;
if (values != null && values.Count > 0)
{
foreach (myClass myValue in values)
{
string Id = myValue.Id;
Desc desc = Enumerations.Descriptions[Convert.ToInt32(Id)] as Desc;
if (desc != null)
{
DataRow dr = tableToPass.NewRow();
dr[0] = key;
dr[1] = desc.Name;
dr[2] = myValue.Timeframes;
tableToPass.Rows.Add(dr);
}
}
}
}
SetTable(tableToPass, isToModify);
}
}
private void SetTable(DataTable table, bool isToModify)
{
try
{
if (isToModify)
{
// Hence we have to append records to existing rows
DataTable existingTable = datagridview.DataSource as DataTable;
if (existingTable != null)
{
table.Merge(existingTable);
datagridview..DataSource = table;
}
else
datagridview..DataSource = table;
}
else
{
datagridview..DataSource = table;
}
datagridview.RowTemplate.Height = 23;
datagridview.ClearSelection();
datagridview.Columns[1].SortMode = datagridview.Columns[2].SortMode = DataGridViewColumnSortMode.NotSortable;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n" + ex.StackTrace);
}
}