最近写了一个程序,界面上只有一个GridControl 控件,用来显示不同分类的数据。
GridControl 显示数据的时候,用户可能设置分组列(如下图)来改变数据的显示样式;下次再次显示该类数据的时候,自动将数据显示成上次显示的样式。(如下图:当前的数据把“asd1”列作为分组列,下次显示数据的是自动把“asd1”列作为分组列)。
如何实现上述的要求呢?
<pre name="code" class="csharp"> //GridView 界面样式的保存路径
private string _templateDirectPath = string.Format("{0}\\TemplateFile", System.Environment.CurrentDirectory);
//GridView 界面样式的名称
private string _templateName = string.Empty;
private void ShowData(DataTable dt)
{
SaveCurrentGridViewLayout();
gridView1.Columns.Clear();
gridControl1.DataSource = dt;
_templateName = dt.Namespace;
LoadCurrentGridViewLayout();
}
//保存当前GridView 的模板
private void SaveCurrentGridViewLayout()
{
//如果GridControl 数据源为空 或者模板文件名称为空 不保存模板。
if (gridControl1.DataSource ==null ||string.IsNullOrEmpty(_templateName))
return;
if (!Directory.Exists(_templateDirectPath))
Directory.CreateDirectory(_templateDirectPath);
string filePath = string.Format("{0}\\{1}}.xml", _templateDirectPath, _templateName);
gridView1.SaveLayoutToXml(filePath);
}
//加载当前 GridView 的界面模板
private void LoadCurrentGridViewLayout()
{
if (string.IsNullOrEmpty(_templateName))
return;
string currentTemplatePath = string.Format("{0}\\{1}.xml", _templateDirectPath, _templateName);
if (!Directory.Exists(_templateDirectPath) || !File.Exists(currentTemplatePath))
return;
gridView1.RestoreLayoutFromXml(currentTemplatePath);
}
注意事项:必须先绑定数据(gridControl1.DataSource = dt;),然后再加在模板(LoadCurrentGridViewLayout();),否则不能正确显示样式。