View Code
1 using System;
2 using System.Data;
3 using System.Configuration;
4 using System.Web;
5 using System.Web.Security;
6 using System.Web.UI;
7 using System.Web.UI.WebControls;
8 using System.Web.UI.WebControls.WebParts;
9 using System.Web.UI.HtmlControls;
10 using System.Data.SqlClient;
11
12 public partial class _Default : System.Web.UI.Page
13 {
14
15
16 SqlConnection sqlcon;
17 SqlCommand sqlcom;
18 string strCon = "Data Source=(local);Database=数据库名;Uid=帐号;Pwd=密码";
19 protected void Page_Load(object sender, EventArgs e)
20 {
21 if (!IsPostBack)
22 {
23 bind();
24 }
25 }
26 protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
27 {
28 GridView1.EditIndex = e.NewEditIndex;
29 bind();
30 }
31
32 //删除
33 protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
34 {
35 string sqlstr = "delete from 表 where id='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
36 sqlcon = new SqlConnection(strCon);
37 sqlcom = new SqlCommand(sqlstr,sqlcon);
38 sqlcon.Open();
39 sqlcom.ExecuteNonQuery();
40 sqlcon.Close();
41 bind();
42 }
43
44 //更新
45 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
46 {
47 sqlcon = new SqlConnection(strCon);
48 string sqlstr = "update 表 set 字段1='"
49 + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "',字段2='"
50 + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim() + "',字段3='"
51 + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim() + "' where id='"
52 + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
53 sqlcom=new SqlCommand(sqlstr,sqlcon);
54 sqlcon.Open();
55 sqlcom.ExecuteNonQuery();
56 sqlcon.Close();
57 GridView1.EditIndex = -1;
58 bind();
59 }
60
61 //取消
62 protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
63 {
64 GridView1.EditIndex = -1;
65 bind();
66 }
67
68 //绑定
69 public void bind()
70 {
71 string sqlstr = "select * from 表";
72 sqlcon = new SqlConnection(strCon);
73 SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
74 DataSet myds = new DataSet();
75 sqlcon.Open();
76 myda.Fill(myds, "表");
77 GridView1.DataSource = myds;
78 GridView1.DataKeyNames = new string[] { "id" };//主键
79 GridView1.DataBind();
80 sqlcon.Close();
81 }
82 }
当鼠标悬浮在行上面上改变颜色
View Code
1 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
2 {
3 //如果是绑定数据行
4 if (e.Row.RowType == DataControlRowType.DataRow)
5 {
6 //鼠标经过时,行背景色变
7 e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#E6F5FA'");
8 //鼠标移出时,行背景色变
9 e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#FFFFFF'");
10 }