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 Tbl = 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","产品类");