经常会用到操作DataSet的时候,简单演示:
protected System.Web.UI.WebControls.DataGrid dg1;
private DataSet myDataSet;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
MakeDataTables();
}
private void MakeDataTables()
{
myDataSet = new DataSet();// 初始化DataSet.
MakeDataTable();//创建表
Bind();//绑定数据
}
private void MakeDataTable()
{
// 创建一个新的DataTable.
System.Data.DataTable myDataTable = new DataTable("myDataTable");
//定义数据列和行.
DataColumn myDataColumn;
DataRow myDataRow;
// 创建新的数据列, 设置数据类型, 列名并添加到DataTable.
myDataColumn = new DataColumn();
myDataColumn.DataType = System.Type.GetType("System.Int32");
myDataColumn.ColumnName = "id";
// myDataColumn.AutoIncrement=true;//自增列
myDataColumn.Unique = true;
// 添加该列到数据集.
myDataTable.Columns.Add(myDataColumn);
// 创建第二个列.
myDataColumn = new DataColumn();
myDataColumn.DataType = System.Type.GetType("System.String");
myDataColumn.ColumnName = "Item";
// 将该列添加到表.
myDataTable.Columns.Add(myDataColumn);
// 设置id为主键.
DataColumn[] PrimaryKeyColumns = new DataColumn[1];
PrimaryKeyColumns[0] = myDataTable.Columns["id"];
myDataTable.PrimaryKey = PrimaryKeyColumns;
// 将数据表添加到DataSet.
myDataSet.Tables.Add(myDataTable);
// 创建三行数据并添加到DataTable
for (int i = 0; i<= 2; i++)
{
myDataRow = myDataTable.NewRow();
myDataRow["id"] = i;
myDataRow["Item"] = "Item " + i;
myDataTable.Rows.Add(myDataRow);
}
}
private void Bind()
{
dg1.DataSource=myDataSet.Tables["myDataTable"];
dg1.DataBind();
}