笔者以前很少使用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","产品类");
新闻热点
疑难解答