DataTable部分代码

//Create DataTable
        DataTable dt = new DataTable();
        dt.CaseSensitive 
= true;
        
//Create DataColumns
        DataColumn col1 = new DataColumn("id"typeof(int));
        DataColumn col2 
= new DataColumn("UserName"typeof(string));
        
//Config Propertyies
        col2.AllowDBNull = false;
        col2.MaxLength 
= 50;
        col2.Unique 
= true;
        

        col1.AutoIncrement 
= true;
        col1.AutoIncrementSeed 
= 100;
        col1.AutoIncrementStep 
= 1;
        col1.ReadOnly 
= true;
        
//the DataColumn with Expression
        DataColumn col3 = new DataColumn("Expression"typeof(string));
        col3.Expression 
= "id+UserName";

        
//add DataColumns to dt;
        dt.Columns.Add(col1);
        dt.Columns.Add(col2);
        dt.Columns.Add(col3);
        dt.PrimaryKey 
= new DataColumn[] { dt.Columns[0] };
        
//Create test data
        DataRow dr = dt.NewRow();
        dr[
1= "Roboth";
        dt.Rows.Add(dr);
        dr 
= dt.NewRow();
        dr[
1= "xinsoft";
        dt.Rows.Add(dr);
        dr 
= dt.NewRow();
        dr[
1= "SpiderMan";
        dt.Rows.Add(dr);
        
//bind to gridview
        this.gridview1.DataSource = dt;
        
this.gridview1.DataBind();

        
//example1 for edit
        DataRow dr1 = dt.Rows.Find(102);
        
        
if (dr1 == null)
        
{
            Response.Write(
"no find");
        }

        
else
        
{
           
            dr1.BeginEdit();
            dr1[
1= "SpiderWoman";
            dr1.EndEdit();
        }

        
//example2 for edit
        object[] obj = new object[] {null,"Spo",null };
        DataRow dr2 
= dt.Rows.Find(102);
        
if (dr2.IsNull(2))//赋值是 DBNull.Value
        {
            
            dr2[
2= "test";
        }

        dr2.ItemArray 
= obj;

        
//example for delete
        DataRow dr_D = dt.Rows.Find(102);
        dr_D.Delete();
        
//Remove corresponding row
        dt.Rows.Remove(dt.Rows.Find(101));
        
////Remove corresponding row again
        dt.Rows.RemoveAt(0);
        
this.gridview2.DataSource = dt;
        
this.gridview2.DataBind();
        DataSet ds 
= new DataSet();
        Response.Write(ds.DataSetName);
posted @ 2008-05-04 18:51  roboth  阅读(246)  评论(0)    收藏  举报