首页 > 代码库 > DataSet用法一:添加代码创建的表DataTable,设置主键外键,读取及修改DataSet表中数据
DataSet用法一:添加代码创建的表DataTable,设置主键外键,读取及修改DataSet表中数据
原文发布时间为:2008-08-01 —— 来源于本人的百度文章 [由搬家工具导入]
using System;
using System.Data;
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 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = new DataSet();
DataTable dt1 = new DataTable("user");
DataTable dt2 = new DataTable("book");
dt1.Columns.Add("uid", typeof(Int32));
dt1.Columns.Add("uname", typeof(string));
dt2.Columns.Add("bid", typeof(Int32));
dt2.Columns.Add("bname", typeof(string));
ds.Tables.Add(dt1);
ds.Tables.Add(dt2);
object[] userdata = http://www.mamicode.com/new object[2];
object[] bookdata = http://www.mamicode.com/new object[2];
userdata[0] = 1;
userdata[1] = "wjwu";
bookdata[0] = 1;
bookdata[1] = "English";
Session["ds"]=ds;
dt1.Rows.Add(userdata);
dt2.Rows.Add(bookdata);
fill();
}
}
private void fill()
{
DataSet ds = new DataSet();
ds = (DataSet)Session["ds"];
GridView1.DataSource = ds.Tables["user"];
GridView1.DataBind();
GridView2.DataSource = ds.Tables["book"];
GridView2.DataBind();
}
protected void addrow_Click(object sender, EventArgs e)
{
//增加表数据
DataSet ds = new DataSet();
ds = (DataSet)Session["ds"];
object[] add = new object[2];
add[0] = 2;
add[1] = "lucy";
try
{
ds.Tables["user"].Rows.Add(add);
Session["ds"] = ds;
fill();
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "')</script>");
}
}
protected void pk_Click(object sender, EventArgs e)
{
//设置主键
DataSet ds = new DataSet();
ds = (DataSet)Session["ds"];
UniqueConstraint uc = new UniqueConstraint("userpk", ds.Tables["user"].Columns["uid"],true);
ds.Tables["user"].Constraints.Add(uc);
Session["ds"] = ds;
fill();
}
protected void fk_Click(object sender, EventArgs e)
{//设置外键
DataSet ds = new DataSet();
ds = (DataSet)Session["ds"];
ForeignKeyConstraint fkc = new ForeignKeyConstraint("userfk", ds.Tables["user"].Columns["uid"], ds.Tables["book"].Columns["bid"]);
ds.Tables["book"].Constraints.Add(fkc);
Session["ds"] = ds;
fill();
}
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = (DataSet)Session["ds"];
Label1.Text = ds.Tables["user"].Rows[0]["uname"].ToString();
}
protected void Button2_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = (DataSet)Session["ds"];
ds.Tables["book"].Rows[0]["bname"] = TextBox1.Text;
Session["ds"] = ds;
fill();
}
}
DataSet用法一:添加代码创建的表DataTable,设置主键外键,读取及修改DataSet表中数据