datagrid如何实现数据行的删除、编辑
datagrid有几列数据,其中前两列为数据,后两列分别显示删除和编辑的超链接,点击超链接就可以对数据进行相关的操作
该如何实现,望指教
谢谢
------解决方案--------------------使用VS2005里面的GridView对象更好哦
------解决方案--------------------如何在DataGrid控件中实现编辑、删除、分类以及分页操作
德仔工作室:http://www.dezai.cn/Article_Show.asp?ArticleID=7680
------解决方案--------------------我用的是2005,这些会对你有帮助的.
好好看看.注意事件.
//删除
32 protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
33 {
34 string sqlstr = "delete from 表 where id='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
35 sqlcon = new SqlConnection(strCon);
36 sqlcom = new SqlCommand(sqlstr,sqlcon);
37 sqlcon.Open();
38 sqlcom.ExecuteNonQuery();
39 sqlcon.Close();
40 bind();
41 }
42
43 //更新
44 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
45 {
46 sqlcon = new SqlConnection(strCon);
47 string sqlstr = "update 表 set 字段1='"
48 + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "',字段2='"
49 + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim() + "',字段3='"
50 + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim() + "' where id='"
51 + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
52 sqlcom=new SqlCommand(sqlstr,sqlcon);
53 sqlcon.Open();
54 sqlcom.ExecuteNonQuery();
55 sqlcon.Close();
56 GridView1.EditIndex = -1;
57 bind();
58 }
59
60 //取消
61 protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
62 {
63 GridView1.EditIndex = -1;
64 bind();
65 }
------解决方案--------------------public partial class _Default : System.Web.UI.Page
{
SqlConnection conn;
protected void Page_Load(object sender, EventArgs e)
{
conn = new SqlConnection("uid=sa;database=northwind");
if (!IsPostBack)
{
//WritePictrue();
GridView1Bind();
}
}
//数据绑定
public void GridView1Bind()
{
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("select employeeid,lastname+firstname as 姓名,city as 城市,address as 地址 from employees", conn);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
//删除事件(先要设置GridView1属性中的数据中的DataKeyNames的值=删除数据库中那一列的列名)
protected void GridView1_DeleteCommand(object source, DataListCommandEventArgs e)
{
//以id为删除条件
string id = GridView1.DataKeys[e.Item.ItemIndex].ToString();
SqlCommand comm = new SqlCommand("delete from employees where employeeid='" + id + "'", conn);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
GridView1Bind();
}
------解决方案--------------------动态设置
public partial class Default2 : System.Web.UI.Page
{
SqlConnection conn;
protected void Page_Load(object sender, EventArgs e)
{
conn = new SqlConnection("uid=sa;database=northwind");
if (!IsPostBack)
{
SetGridStyle();
SetField();
GridBind();
}