最近寫了一個程式,界面上隻有一個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();),否則不能正确顯示樣式。