datagrid|window|建立|資料
筆者以前很少使用vs.net中的datagrid,原因是覺得不是很好用,昨天突然想起來,用一個簡單的類,來實現手工建立資料列,這樣可以自訂欄名和綁定資料欄位,使用起來比較方面的~~
類:exDataGrid.cs
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace WindowsApplication5
{
/// <summary>
/// exDataGrid 的摘要說明。
/// </summary>
public class exDataGrid
{
private System.Windows.Forms.DataGrid dataGrid;
private string strMapName;
private static DataGridTableStyle dgt;
//StrMapName:表名;
public exDataGrid(System.Windows.Forms.DataGrid DataGrid,string StrMapName)
{
this.dataGrid=DataGrid;
this.strMapName=StrMapName;
dataGrid.TableStyles.Clear();
DataGridTableStyle TblStyle = new DataGridTableStyle();
TblStyle.MappingName = this.strMapName;
dataGrid.TableStyles.Add(TblStyle);
dgt=TblStyle;
}
//參數:
//1--i:GridColumnStyles;
//2--strMap:MappingName ;
//3--strHeader:HeaderText
public static void CreateCols(int i,string strMap,string strHeader)
{
CreateCols(i,strMap,strHeader,80);
}
//參數:
//intwidth:資料列列寬
public static void CreateCols(int i,string strMap,string strHeader,int intwidth)
{
//在這裡可以設定列的樣式
DataGridColumnStyle TextCol = new DataGridTextBoxColumn();
DataGridTableStyle TblStyle=dgt;
TblStyle.GridColumnStyles.Add(TextCol);
TblStyle.GridColumnStyles[i].MappingName = strMap;
TblStyle.GridColumnStyles[i].HeaderText = strHeader;
TblStyle.GridColumnStyles[i].Width = intwidth;
TblStyle.GridColumnStyles[i].NullText = string.Empty;
}
}
}
調用:
this.dataGrid1.SetDataBinding(dataSet, "tableName");
exDataGrid edg =new exDataGrid(this.dataGrid1,"tableName");
exDataGrid.CreateCols(0,"ProductCode","產品編號");
exDataGrid.CreateCols(1,"ProductName","產品名稱");
exDataGrid.CreateCols(2,"ProductClass","產品類");