using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Configuration;
namespace DataGridTest
{
/// <summary>
/// WebForm1 的摘要说明。
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid dg;
public int lastIndex=0;
private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
dgBind();
}
}
SqlConnection conn=new SqlConnection(ConfigurationSettings.AppSettings["SqlConn"].ToString());
public void dgBind()
{
string sql="select employeeid,lastname,birthdate,city from employees";
SqlDataAdapter da=new SqlDataAdapter(sql,conn);
DataSet ds=new DataSet();
da.Fill(ds);
dg.DataSource=ds;
dg.DataBind();
}
private void dg_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
int id=(int)dg.DataKeys[e.Item.ItemIndex];
string sql="delete employees where employeeid="+id.ToString();
SqlCommand comm=new SqlCommand(sql,conn);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
lastIndex=dg.CurrentPageIndex;
if((dg.PageCount-dg.CurrentPageIndex==1)&&dg.Items.Count==1)
{
if(dg.PageCount>1)
{
lastIndex-=1;
}
else
{
lastIndex=0;
}
}
dg.CurrentPageIndex=lastIndex;
dgBind();
}
private void dg_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
{
dg.CurrentPageIndex=e.NewPageIndex;
dgBind();
}
private void dg_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if(e.Item.ItemType==ListItemType.Item||e.Item.ItemType==ListItemType.AlternatingItem)
{
LinkButton lb=(LinkButton)e.Item.Cells[3].Controls[0];
lb.Attributes.Add("onclick","return confirm('你确实要删除吗')");
}
}
private void dg_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
dg.EditItemIndex=e.Item.ItemIndex;
dgBind();
}
private void dg_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
dg.EditItemIndex=-1;
dgBind();
}
private void dg_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
int id=(int)dg.DataKeys[e.Item.ItemIndex];
TextBox city=(TextBox)e.Item.Cells[2].FindControl("txtCity");
string sql="update employees set city='"+city.Text+"' where employeeid="+id;
SqlCommand comm=new SqlCommand(sql,conn);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
dg.EditItemIndex=-1;
dgBind();
}
}
}