在ADO.NET中,DataTable本身可以脱离数据库进行使用,对DataTable数据的更改与数据库并没有关系,这些更改都是在内存中修改数据。

 【方法一】

DataTable类表示一个数据表,可以通过以下两种方法创建:

1、通过数据库操作从数据库获取;

2、直接通过DataTable的构造函数创建。

上一个章节的方法时采用第二种的。

(1)通过DataTable类的构造函数创建一个DataTable对象,

     方法一:DataTable dt=new DataTable();//创建一个表名为空字符串的数据表

     方法二:DataTable dt=new DataTable(string TableName);//创建一个表名为TableName的数据表

      例如:DataTable dt=new DataTable("userInfo");

(2)创建多个DataColumn对象,并依次添加到DataTable的Column属性中。常用格式有三种:

     a、DataColumn(string name,Type ty):创建一个列名为name、类型为ty的数据列,DataType可以是数据库支持的任意数据类型;

     例如:DataColumn col= new DataColumn("username",typeof(string));

     或者:或者可以这样定义,以便减少代码的书写

     前面已经定义了DataTable的对象dt了,这里我们可以可以这样写:

DataSet dsnew = new DataSet();
                 DataTable dtNew = new DataTable();
                 DataColumn col = new DataColumn("class", typeof(string));                dtNew.Columns.Add(col);
                dtNew.Columns.AddRange(new DataColumn[]{
             new DataColumn("newName",typeof(string)),
             new DataColumn("other",typeof(string))

     b、DataColumn(string name,Type ty,string expr):创建一个列名为name、类型为ty的数据列,参数expr指定用于创建该列的表达式。

     c、  dt.Columns.Add("产品名称", typeof(string));

(3)通过DataTable.NewRow()方法,获取DataRow对象,并且设置对应字段的属性,将该DataRow对象添加到DataTable类的Rows属性中。

      》》添加一个记录

  A、方法一:

  

DataRow row = dt.NewRow();
       row["username"]="张三";
       row["Age"]=25;
       row["Mobile"]="12345678910";
       dt.Rows.Add(row);
       // *********************(另一种方法)

 B、方法二

        dt.Rows.Add(new Object[]{"",21,"15923647810"});

*****************************************************************************************************************************************************

【方法二】

除了以上方法,还可以按照以下方法进行:

         

DataSet ds = new DataSet();
             DataTable dt = new DataTable();            dt.Columns.Add("产品名称", typeof(string));
             dt.Columns.Add("供应商编号", typeof(string));
             dt.Columns.Add("类别编号", typeof(string));
             dt.Columns.Add("单位数量", typeof(string));
             dt.Columns.Add("产品单价", typeof(string));
             dt.Columns.Add("库存量", typeof(string));
             dt.Columns.Add("已订购量", typeof(string));
             dt.Columns.Add("安全存量", typeof(string));
             dt.Columns.Add("IsSale", typeof(string));
             dt.Columns.Add("Remark", typeof(string));
             dt.Columns.Add("Id_Department", typeof(string));

            ds.Tables.Add(dt);            ViewState["DS_PRODUCTIONPLAN"]=ds;

--------------------------------------------------------------------------------------------------------------------------------------------

((DataSet)ViewState["DS_PRODUCTIONPLAN"]).Tables[0].NewRow();//生成新行
            【方法1】     //dr["产品名称"] = TextProName.Text.Trim();//也可以用这种方法                //dr["供应商编号"]=TextProID.Text.Trim();
                //dr["类别编号"]=TextProID.Text.Trim();

【方法2】 //也可以采用如下方法:使用DataRow对象dr的属性ItemArray进行                dr.ItemArray= new object[]{
      

TextProName.Text.Trim(),
                 TextProID.Text.Trim(),
                 TextProClass.Text.Trim(),
                 TextProNum.Text.Trim(),
                 TextProPrice.Text.Trim(),
                 TextProStoreNum.Text.Trim(),
                 TextProBookNum.Text.Trim(),
                 TextProSafeNum.Text.Trim(),
                 DropDownList1.SelectedItem.Text.Trim(),
                 TextRemark.Text,
                 Convert.ToDecimal(Session["WSH_ID"])//部门编号
                 };                ((DataSet)ViewState["DS_PRODUCTIONPLAN"]).Tables[0].Rows.Add(dr);//往表格填数据

 

 【栗子证明】

protected void BtnOKNow_Click(object sender, EventArgs e)
         {
             if (TxtClass.Text.Trim() != "" && TxtNewName.Text.Trim() != "" && TxtOther.Text.Trim() != "")
             {
                 DataSet dsnew = new DataSet();
                 DataTable dtNew = new DataTable();
                 DataColumn col = new DataColumn("class", typeof(string));
                 dtNew.Columns.Add(col);
                 dtNew.Columns.AddRange(new DataColumn[]{
             new DataColumn("newName",typeof(string)),
             new DataColumn("other",typeof(string))
             });
                 dsnew.Tables.Add(dtNew);                DataRow drnew = dtNew.NewRow();
                 drnew["class"] = TxtClass.Text.Trim();
                 drnew["newName"] = TxtNewName.Text.Trim();
                 drnew["other"] = TxtOther.Text.Trim();                /*方法二*/drnew.ItemArray = new object[] {
                 //TxtClass.Text.Trim(),
                 //TxtNewName.Text.Trim(),
                 //TxtOther.Text.Trim()
                 //};
                dsnew.Tables[0].Rows.Add(drnew);                Gdv.DataSource = dsnew;
                 Gdv.DataBind();
            }
             else
             {
                 Response.Write("信息不完整");
             }
         }

 【示例演示】

using System;
 using System.Data;
 using System.Data.SqlClient;
 using System.Configuration;
 using System.Collections;
 using System.Web;
 using System.Web.Security;
 using System.Web.UI;
 using System.Web.UI.WebControls;
 using System.Web.UI.WebControls.WebParts;
 using System.Web.UI.HtmlControls;public partial class DataSet_InsertData : System.Web.UI.Page
 {
     private string strConn = "data source=localhost;initial catalog=Northwind;user id=sa;password=sa";
     SqlConnection Conn;
     SqlDataAdapter myDataAdapter;
     DataSet myDataSet;
     protected void Page_Load(object sender, EventArgs e)
     {
         Conn = new SqlConnection(strConn);
         string strSql = "SELECT * FROM Categories";
         myDataAdapter = new SqlDataAdapter(strSql, Conn);
         //创建CommandBuilder对象,该对象可以自动创建用于插入、删除及更新的SQL语句
         SqlCommandBuilder myCB = new SqlCommandBuilder(myDataAdapter);        if (!IsPostBack)
         {
             //调用FillGridView()方法,用以显示数据
             FillGridView();
         }
     }
     private void FillGridView()
    {
         myDataSet = new DataSet();
         Conn.Open();
         myDataAdapter.Fill(myDataSet, "Categories");        Conn.Close();
         myGridView.DataSource = myDataSet.Tables["Categories"];        myGridView.DataBind();
     }
     protected void OK_Click(object sender, EventArgs e)
     {
         DataSet InsertDataSet = new DataSet();
         Conn.Open();
         myDataAdapter.Fill(InsertDataSet, "Categories");
         Conn.Close();
         //创建一个新行,准备添加新的数据                                                               【1】
         DataRow insertRow = InsertDataSet.Tables["Categories"].NewRow();
        //指定新行中每一个字段的值                                                                           【2】
         insertRow["CategoryName"] = txtCategoryName.Text;
         insertRow["Description"] = txtDescription.Text;
        //将创建并填充数据的行insertRow添加到InsertDataSet中的Categories表格中【3】
         InsertDataSet.Tables["Categories"].Rows.Add(insertRow);
        //使用DataAdapter对象的Update方法更新插入新行后的数据表Categories        【4】
         myDataAdapter.Update(InsertDataSet.Tables["Categories"]);
        txtCategoryName.Text = "";
         txtDescription.Text = "";
         //调用FillGridView()方法,重新显示插入新行后的数据信息                        【5】
         FillGridView();
    }
 }

 

*****************************************如何获取数据集ds中的字段和数据********************************************************************************

*******
DataRow row = ds.Tables[0].Rows[0];

string title = row["title"].ToString();
string keyword = row["keyword"].ToString();
string source = row["source"].ToString();
string sourceUrl = row["source_url"].ToString();
string Abstract = row["ABSTRACT"].ToString();
string Content = row["content"].ToString();
string LastMod_UserId = row["LastMod_UserId"].ToString();
string Res_filenum = row["Res_filenum"].ToString();
string Cat_id = row["Cat_id"].ToString();
string Info_filename = row["Info_filename"].ToString();
string Info_ABS_Path = row["Info_ABS_Path"].ToString();
string Info_Rel_Path = row["Info_Rel_Path"].ToString();
string Full_Path = row["Full_Path"].ToString();

【方法三】

protected void Button2_Click(object sender, EventArgs e)
         {
             //插入记录
             string conString = "data source=127.0.0.1;initial catalog=codematic;user id=sa;password=";
             string strSQL = "SELECT * FROM P_Product";
             SqlConnection myConnection = new SqlConnection(conString);
             DataSet ds = new DataSet();
             myConnection.Open();
             SqlDataAdapter adapter = new SqlDataAdapter(strSQL, myConnection);
             adapter.Fill(ds, "Product");
             myConnection.Close();             DataRow drAdd = ds.Tables["Product"].NewRow();
             drAdd["ProductId"] = "001";
             drAdd["CategoryId"] = "002";
             drAdd["BrandId"] = "003";
             drAdd["Name"] = "test";
             drAdd["Descn"] = "this is good";
             ds.Tables["Product"].Rows.Add(drAdd);            SqlCommandBuilder myBuilder = new SqlCommandBuilder(adapter);
             adapter.Update(ds, "Product");         }