asp之gridview学习小记

开始学习asp,这两天主要学习了gridview的一些实用性操作,记下来备忘。
代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
using System.Data;


namespace mynet
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        private MySqlConnection mysql;
        private MySqlCommand mysqlcomm;
        string strmysql = "Database=myweb;Data Source = 127.0.0.1;User Id=root;password=mysqlpassword;port=3306";
        private static DataTable dt;
        public void DataInit()
        {
            Random ra = new Random();
            int i = 0;
            try
            {
                for (i = 0; i < 20; i++)
                {
                    string insert = string.Format("insert into student (id,name,address) values ({0},’aaa’,’dddd’)", ra.Next(1, 100));
                    MySqlCommand mysqlcomm = new MySqlCommand(insert, mysql);
                    mysqlcomm.ExecuteNonQuery();
                }
            }
            catch (MySqlException ex)
            {
                i--;
                Response.Write(ex.Message);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            mysql = new MySqlConnection(strmysql);
            mysql.Open();
          //  DataInit();
            if (!IsPostBack)
            {
              

                BindData();
                //  DataInit();
            }
        }

        public void BindData()
        {
            string sqlstr = "select * from student";
            MySqlDataAdapter myda = new MySqlDataAdapter(sqlstr, mysql);
            dt = new DataTable();
            myda.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                dt.Columns.Add("item");
                for (int i = 0; i < dt.Rows.Count; i++)
                    dt.Rows[i]["item"] = i + 1;
            }
            GridView1.DataSource = dt;
            GridView1.DataKeyNames = new string[] { "id" };
            GridView1.DataBind();
        }

        public void Bind()
        {
         
            string sqlstr = "select * from student";
            MySqlDataAdapter myda = new MySqlDataAdapter(sqlstr, mysql);
            dt = new DataTable();
            myda.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                dt.Columns.Add("item");
                for (int i = 0; i < dt.Rows.Count; i++)
                    dt.Rows[i]["item"] = i + 1;
            }
            GridView1.DataSource = dt;
            GridView1.DataKeyNames = new string[] { "id" };
            GridView1.DataBind();
        }
        //删除
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string sqlstr = "delete from student where id='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
            mysqlcomm = new MySqlCommand(sqlstr, mysql);
            mysqlcomm.ExecuteNonQuery();
            Bind();
        }
        //编辑
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            Bind();

        }
        //更新
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            string sqlstr = "update student set id='" +
          ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "', name = '" +
          ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim() + "', address = '" +
          ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim() + "' where id ='" +
          GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
            mysqlcomm = new MySqlCommand(sqlstr, mysql);
            mysqlcomm.ExecuteNonQuery();
            GridView1.EditIndex = -1;
            Bind();
        }
        //取消
        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            Bind();
        }

        public void BindView()
        {
            string sqlstr = "select * from student";
            MySqlDataAdapter myda = new MySqlDataAdapter(sqlstr, mysql);
            dt = new DataTable();
            myda.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                dt.Columns.Add("item");
                for (int i = 0; i < dt.Rows.Count; i++)
                    dt.Rows[i]["item"] = i + 1;
            }
            DataView view = dt.DefaultView;
           string sortExpressing = this.GridView1.Attributes["SortExpression"];
           string sortDirection = this.GridView1.Attributes["SortDirection"];
           string sort = sortExpressing + " " + sortDirection;
           view.Sort = sort;
           GridView1.DataSource = view;
           GridView1.DataBind();

         //   string 
            
        }

        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sortExpressing = e.SortExpression.ToString();
            string sortDirection = "ASC";
            if (sortExpressing == this.GridView1.Attributes["SortExpression"])
            {
                sortDirection = (this.GridView1.Attributes["SortDirection"] == sortDirection ? "DESC" : "ASC");
            }
            this.GridView1.Attributes["SortExpression"] = sortExpressing;
            this.GridView1.Attributes["SortDirection"] = sortDirection;
            BindView();
        }

        //行变色
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            int i;
            for (i = 0; i < GridView1.Rows.Count; i++)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#00A9FF'");
                    e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
                }
            }
        }


     
      
    }
}

前台主要代码

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="mynet.WebForm2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>

            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" 
                OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting" 
                OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating"
                 AllowSorting="true" OnSorting="GridView1_Sorting" OnRowDataBound="GridView1_RowDataBound">
                <Columns>
                    <asp:BoundField DataField="item" HeaderText="编号" />
                    <asp:BoundField DataField="id" HeaderText="ID" SortExpression="id" />
                    <asp:BoundField DataField="name" HeaderText="姓名" />
                    <asp:CommandField HeaderText="选择" ShowSelectButton="True" />
                    <asp:CommandField HeaderText="编辑" ShowEditButton="True" />
                    <asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
                </Columns>
            </asp:GridView>

        </div>
    </form>
</body>
</html>

发表评论

电子邮件地址不会被公开。 必填项已用*标注