C#中datatable的用法/传数据
在开发中,我们常用到表类型数据,不同于string,int。。。。那么datatable类型如何定义呢,具体怎么使用呢,代码如下:
namespace Common.Table { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Runtime.Serialization; [System.ComponentModel.DesignerCategory("Code")] [SerializableAttribute] public class dataTableName : DataTable { public const string dataTableName_TABLENAME = "dataTableName "; public const string FILE_ID_FIELD = "FILE_ID"; public const string APPLYER_FIELD = "APPLYER"; public const string YEARMONEY_FIELD = "YEARMONEY"; public const string COMPANY_NAME_FIELD = "COMPANY_NAME"; public dataTableName () { BuildDataTables(); } public dataTableName (SerializationInfo info, StreamingContext context) : base(info, context) { } private void BuildDataTables() { this.TableName = dataTableName_TABLENAME ; this.Columns.Add(FILE_ID_FIELD, typeof(System.String)); this.Columns.Add(APPLYER_FIELD, typeof(System.String)); this.Columns.Add(YEARMONEY_FIELD, typeof(System.Double)); this.Columns.Add(COMPANY_NAME_FIELD, typeof(System.String)); } } }
表数据类型已经定义完成,通常表类型中列的名字和列的个数都是和表名都是和数据库中的表是一致的,这样方便数据库的操作
废话不多说,具体使用方法如下:
public dataTableName table1 //申明一个表类型数据的属性,方便下面使用 { get { return ((ViewState["table1"] == null) ? null : (dataTableName )ViewState["table1"]); } set { ViewState["table1"] = value; } } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { table1 = new dataTableName ();//页面加载时要实例化,不然会报‘未将对象引用到实例’的错误 } } protected void lbtnSave_Click(object sender, EventArgs e) { DataRow row = null; row = dataTableName.NewRow(); table1 .Rows.Add(row); row[dataTableName .FILE_ID_FIELD] = values1; row[dataTableName .APPLYER_FIELD] = values2;
table1 .AcceptChanges();
datatable.DefaultView.Sort = "columnName desc";//排序 }
调用时的代码:
System mySystem = new System();
myData = mySystem.mothed(myFamilyInfoTable);
接收参数:
public calss System
{
public DataSet mothed( dataTableName table2);
}
ok,