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;
using System.Data.SqlClient;
public partial class Default5 : System.Web.UI.Page
{
DataTable dtTemp = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
databind();//一定要写成一个方法,不然不成功!!!!
}
}
protected void databind()
{
DataTable dt = new DataTable();
string constr = "server=.;uid=sa;pwd=huwei;database=Km";
string sql = "select * from km_info ";
SqlConnection conn = new SqlConnection(constr);
SqlCommand com = new SqlCommand(sql, conn);
SqlDataAdapter da = new SqlDataAdapter(com);
da.Fill(dt);
if (ViewState["dt"] == null) //判断是内存中是否存在这张表
{
ViewState["dt"] = dt;
}
GridView1.DataSource = (DataTable)ViewState["dt"]; //让girdview数据源指定内存中的表,而不是读出来的dt,因为页面每次都要刷新,才能正确显示,所有每次都是原来内容,达不到修改后的效果
GridView1.DataBind();
Label1.Text = DateTime.Now.ToString();
}
//点击编辑
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
databind();
}
//点击更新
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "a", "alert('" + ((TextBox)GridView1.Rows[GridView1.EditIndex].Cells[2].Controls[0]).Text + "');", true);
int id = Convert.ToInt32(((TextBox)GridView1.Rows[GridView1.EditIndex].Cells[1].Controls[0]).Text);//获取id行(主键)
dtTemp = (DataTable)ViewState["dt"];
dtTemp.PrimaryKey = new DataColumn[] { dtTemp.Columns["km_id"] };//建立一个主键
DataRow row = dtTemp.Rows.Find(id);//找到主键等于id的行
row[1] = ((TextBox)GridView1.Rows[GridView1.EditIndex].Cells[2].Controls[0]).Text;
ViewState["dt"] = dtTemp;
GridView1.EditIndex = -1;
databind();
}
//点击取消
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
databind();
}
//删除
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "a", "return confirm('确定删除否?');", true);
int n = e.RowIndex;//获取但前第几行
string id = GridView1.Rows[n].Cells[1].Text;//找到该行第一列(id)列 也就是主键
dtTemp = (DataTable)ViewState["dt"];
dtTemp.PrimaryKey = new DataColumn[] { dtTemp.Columns["km_id"] };//建立一个主键
DataRow row = dtTemp.Rows.Find(id);//找到主键等于id的行
dtTemp.Rows.Remove(row);
ViewState["dt"] = dtTemp;
databind();
}
//绑定数据时,表头显示背景图片
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Attributes.Add("style", "background-image:url('App_Themes\\Office2003 Blue\\GridView\\gvGradient.gif')");
}
}
//分页
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
databind();
}
}