我有两个选项卡,一个是Tab1做普通验证,另一个是Tab2,它有一个datagridview,它的源是一个用来自csv的数据填充的datatable。当我从Tab1导航到Tab2时,转换并不顺利。当我从Tab2切换到Tab1,然后又切换回Tab2时,网格正在重新加载数据,表单冻结了一段时间。有没有一种方法可以让我们缓存datagrid内容,而不是每次都重新加载?
private void Tab_Selected(Object sender, TabControlEventArgs e)
{
if (e.TabPage == Tab1)
{
WindowState = FormWindowState.Maximized;
Grid.Size = new System.Drawing.Size(1920, 1080);
Tab.Size = new Size(1920, 1080);
Grid.Dock = DockStyle.Fill;
try
{
foreach (string f in Directory.GetFiles(dir, "HSPP*"))
{
LoadData(f);
}
}
catch (Exception ex)
{
MessageBox.Show("Exception raised:" + ex.Message);
}
}
else
{
Tab.BindingContext = this.BindingContext;
this.WindowState = FormWindowState.Normal;
}
}
public void LoadData(String FileName)
{
string header_text = "<a bunch of headers>";
string[] headers;
string[] fields;
ArrayList schoolids = new ArrayList();
DataTable dt = new DataTable();
BindingSource source = new BindingSource();
TextFieldParser tp = new TextFieldParser(FileName);
DataRow dr;
Grid.AllowUserToAddRows = false;
headers = header_text.Split(new char[] { ',' });
tp.TextFieldType = FieldType.FixedWidth;
tp.SetFieldWidths(new int[33] { 10, 8, 8, 35, 35, 35, 35, 20, 15, 40, 40, 30, 30, 40, 25, 3, 12, 15, 10, 10, 8, 25, 15, 40, 60, 80, 3, 5, 5, 5, 41, 1, 30 });
try
{
for (int i = 0; i < headers.Length; i++)
dt.Columns.Add(headers[i]);
while (!tp.EndOfData)
{
dr = dt.NewRow();
fields = tp.ReadFields();
for (int i = 0; i < fields.Count(); i++)
dr[i] = fields[i].ToUpper();
dt.Rows.Add(dr);
}
source.DataSource = dt;
Grid.DataSource = source;
foreach (DataGridViewRow row in Grid.Rows)
{
if (!schoolids.Contains(row.Cells[8].Value))
schoolids.Add(row.Cells[8].Value);
}
ValidateData(schoolids);
}
catch (Exception e) { MessageBox.Show(e.ToString()); }
}发布于 2016-08-31 23:16:35
谢谢@Rakitic。我实现了这个方法来缓存数据文件,并在Form_Load事件中调用了这个方法:
private Boolean CacheDataFile(String file)
{
CacheItemPolicy policy = new CacheItemPolicy();
List<string> filepaths = new List<string>();
string filecontents = cache["insidefile"] as string;
string path = new FileInfo(file).FullName;
filepaths.Add(path);
policy.ChangeMonitors.Add(new HostFileChangeMonitor(filepaths));
filecontents = File.ReadAllText(path);
cache.Set("insidefile", filecontents, policy);
return true;
}https://stackoverflow.com/questions/39241164
复制相似问题