没别的说,看代码就可以了,cs文件里加上了很全的注释,对DataTable的操作,初始化、修改、添加、删除、检索全都有了
DTinGridView.aspx
DTinGridView.aspx.cs
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 test_DTinGridView : System.Web.UI.Page
{
protected static DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if (dt == null)
{
//初始化DataTable
dt = new DataTable("opTable");
//定义数据类型
System.Type stringType = System.Type.GetType("System.String");
System.Type intType = System.Type.GetType("System.Int16");
//添加列
dt.Columns.Add(new DataColumn("step", intType));
dt.Columns.Add(new DataColumn("uid", intType));
dt.Columns.Add(new DataColumn("una", stringType));
//添加行
dt.Rows.Add(new object[] { 1, 1, "阿一" });
dt.Rows.Add(new object[] { 2, 2, "阿二" });
dt.Rows.Add(new object[] { 3, 3, "阿三" });
dt.Rows.Add(new object[] { 4, 4, "阿四" });
dt.Rows.Add(new object[] { 5, 5, "阿五" });
dt.Rows.Add(new object[] { 6, 6, "阿六" });
//保存
dt.AcceptChanges();
}
if (!IsPostBack)
{
ShowDataInGridView();
}
}
private void ShowDataInGridView()
{
//用GridView显示,查看现在的数据
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
//添加
int step,uid;
string una;
//取添加的信息
step = Convert.ToInt16(TextBoxAddRow.Text);
uid = Convert.ToInt32(TextBoxAddUid.Text);
una = TextBoxAddUna.Text;
//把step后的行,step值 + 1,保证step值按顺序唯一
ReSetStep(dt, step, true);
if (step == 0)
{
//保存编号从1开始
step = 1;
}
else
{
step++;
}
//添加行
dt.Rows.Add(new object[] { step, uid, una });
//保存
dt.AcceptChanges();
//显示结果
ShowDataInGridView();
}
protected void ButtonDel_Click(object sender, EventArgs e)
{
//删除
int step;
//取删除信息
step = Convert.ToInt16(TextBoxDelRow.Text);
//删除行
DeleteDataFromDT(dt, step);
//把被删除的行后面的行,step值 - 1,保证step值不会跳值
ReSetStep(dt, step, false);
//保存
dt.AcceptChanges();
//显示结果
ShowDataInGridView();
}
protected void Button3_Click(object sender, EventArgs e)
{
//修改
int step,rowIndex;
string una;
//取修改信息
step = Convert.ToInt16(TextBoxEditRow.Text);
rowIndex = step - 1;
una = TextBoxEditUna.Text;
//按指定行号修改
dt.Rows[rowIndex].BeginEdit();
dt.Rows[rowIndex]["una"] = una;
dt.Rows[rowIndex].EndEdit();
dt.AcceptChanges();
//显示结果
ShowDataInGridView();
}
private void DeleteDataFromDT(DataTable dt, int step)
{
//从DataTable里按条件删除行
DataRow[] drs = dt.Select("step=" + step.ToString());
foreach (DataRow dr in drs)
{
dt.Rows.Remove(dr);
}
dt.AcceptChanges();
}
private void ReSetStep(DataTable dt, int step, bool isAdd)
{
//更新step值
int stepTemp, increment;
DataView dv;
if (isAdd)
{
increment = 1;
}
else
{
increment = -1;
}
foreach (DataRow dr in dt.Rows)
{
stepTemp = Convert.ToInt16(dr["step"]);
if (stepTemp > step)
{
dr.BeginEdit();
dr["step"] = stepTemp + increment;
dr.EndEdit();
}
}
dv = dt.DefaultView;
dv.Sort = "step Asc";
dt = dv.Table;
dt.AcceptChanges();
}
}