DataSet对象使用XML格式来存储数据,DataSet可以脱离数据源。
protected void Page_Load(object sender, EventArgs e)
{
DataSet myds = new DataSet();
DataTable mydt = new DataTable("Squares");
DataRow mydr;
mydt.Columns.Add(new DataColumn("数字", typeof(Int32)));
mydt.Columns.Add(new DataColumn("平方", typeof(Int32)));
for (int i = 0; i < 10; i++)
{
mydr = mydt.NewRow();
mydr[0] = i;
mydr[1] = i * i;
mydt.Rows.Add(mydr);
}
myds.Tables.Add(mydt);
dg1.DataSource = myds.Tables["Squares"].DefaultView;
dg1.DataBind();
}
如果DataSet对象是从数据源读取的数据,可以对DataSet对象进行添加、删除和修改等操作。{
DataSet myds = new DataSet();
DataTable mydt = new DataTable("Squares");
DataRow mydr;
mydt.Columns.Add(new DataColumn("数字", typeof(Int32)));
mydt.Columns.Add(new DataColumn("平方", typeof(Int32)));
for (int i = 0; i < 10; i++)
{
mydr = mydt.NewRow();
mydr[0] = i;
mydr[1] = i * i;
mydt.Rows.Add(mydr);
}
myds.Tables.Add(mydt);
dg1.DataSource = myds.Tables["Squares"].DefaultView;
dg1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Server.MapPath("person.mdb");
conn.Open();
string sql = "select * from grade";
OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds, "grade");
DataTable dt = ds.Tables["grade"];
DataRow row = dt.NewRow();
row["学号"] = 14;
row["性别"] = "男";
row["姓名"] = "小齐";
row["语文"] = 78;
row["数学"] = 98;
row["英语"] = 91;
dt.Rows.Add(row);
OleDbCommandBuilder cb = new OleDbCommandBuilder(da);
da.Update(ds, "grade");
dg.DataSource = ds.Tables["grade"].DefaultView;
dg.DataBind();
conn.Close();
}
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Server.MapPath("person.mdb");
conn.Open();
string sql = "select * from grade";
OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds, "grade");
DataTable dt = ds.Tables["grade"];
DataRow row = dt.NewRow();
row["学号"] = 14;
row["性别"] = "男";
row["姓名"] = "小齐";
row["语文"] = 78;
row["数学"] = 98;
row["英语"] = 91;
dt.Rows.Add(row);
OleDbCommandBuilder cb = new OleDbCommandBuilder(da);
da.Update(ds, "grade");
dg.DataSource = ds.Tables["grade"].DefaultView;
dg.DataBind();
conn.Close();
}