Asp.Net 控件 GridView

这两天做的作业都得用到visual studio 越来越发现其功能真心强大

前几天Asp.Net做了个界面增删查改的作业(连接数据库),用到了个组件GridView,感觉很强大

在这里小结一下(这里主要说下字段和事件):

字段,
BoundField显示数据源中某个字段的值。这是 GridView控件的默认列类型。
ButtonField为 GridView控件中的每个项显示一个命令按钮。可以创建一列自定义按钮控件,如“添加”按钮或“移除”按钮。
CheckBoxField为 GridView控件中的每一项显示一个复选框。此列字段类型通常用于显示具有布尔值的字段。
CommandField 显示用来执行选择、编辑或删除操作的预定义命令按钮。
HyperLinkField将数据源中某个字段的值显示为超链接。此列字段类型允许您将另一个字段绑定到超链接的 URL。
ImageField为 GridView控件中的每一项显示一个图像。
TemplateField根据指定的模板为 GridView控件中的每一项显示用户定义的内容。此列字段类型允许您创建自定义的列字段。


事件,
RowCancelingEdit 在一个处于编辑模式的行的Cancel按钮被单击,但是在该行退出编辑模式之前发生。
RowCommand单击一个按钮时发生。
RowCreated创建一行时发生。 
RowDataBound一个数据行绑定到数据时发生。
RowDeleting, RowDeleted 这两个事件都是在一行的Delete按钮被单击时发生。它们分别在该网格控件删除
该行之前和之后激发。
RowEditing当一行的Edit按钮被单击时,但是在该控件进入编辑模式之前发生。
RowUpdating,RowUpdated这两个事件都是在一行的Update按钮被单击时发生。它们分别在该网格控件更
新该行之前和之后激发。
SelectedIndexChanging, SelectedIndexChanged这两个事件都是在一行的Select按钮被单击时发生。
它们分别在该网格控件处理选择操作之前和之后激发。 
Sorting, Sorted这两个事件都是在对一个列进行排序的超链接被单击时发生。
它们分别在网格控件处理排序操作之前和之后激发

接下来把作业拿出来分析几个事件:

之前我已说过如何连接Mysql数据库,这个界面增删查改作业也是基于那个基础,当然也是之前那个界面

我把添加页面写在同一个界面上,理解就行,代码:

界面,

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

<!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 style="height: 34px">
    
    <form id="form1" runat="server">

        <div id="container">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"  Font-Size="12px" Width="591px" CellPadding="4" ForeColor="#333333" GridLines="None"
            OnRowDeleting="GridView1_RowDeleting" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowCommand="GridView1_RowCommand"
            OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit"
            >
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
          <Columns>
            
            <asp:BoundField DataField="s_no" HeaderText="学号" />
            <asp:BoundField DataField="s_name" HeaderText="名字" />
            <asp:BoundField DataField="s_age" HeaderText="年龄" />
            <asp:BoundField DataField="s_sex" HeaderText="性别" />
            <asp:CommandField HeaderText="编辑" ShowEditButton="true"/>
              <asp:CommandField HeaderText="删除" ShowDeleteButton="true">
                  
              </asp:CommandField>
              
          </Columns>
            
            <EditRowStyle BackColor="#999999" />
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#E9E7E2" />
            <SortedAscendingHeaderStyle BackColor="#506C8C" />
            <SortedDescendingCellStyle BackColor="#FFFDF8" />
            <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
            
        </asp:GridView>
  
         <br />
        <br />
       
         学号:
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
        名字:
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
        年龄:
        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox><br />
        性别:
        <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
         <p>
            <asp:Button ID="Btn_add" runat="server" Text="添加" OnClick="Btn_add_Click" />
        </p>

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


实现类,

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


namespace DataRefresh
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        MySqlConnection mySqlConn;//mysql连接对象

        protected void Page_Load(object sender, EventArgs e)
        {
            string connStr = "Database=myschool;Data Source=localhost;User Id=root;Password=123";//连接字符串
            mySqlConn = new MySqlConnection(connStr);
            mySqlConn.Open();
            if (!IsPostBack)
            {
                bind();
            }
        }

        public void bind()
        {
            //创建MySqlDataAdapter对象执行查询
            MySqlDataAdapter DataAdapter = new MySqlDataAdapter("select * from student", mySqlConn);
            DataSet dataset = new DataSet();
            // 填充DataSet对象
            DataAdapter.Fill(dataset, "student");
            //将数据显示在gridview中
            GridView1.DataSource = dataset;
            GridView1.DataKeyNames = new string[] { "s_no" };//主键
            GridView1.DataBind();
            
        }


        //删除
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string sqlStr = "delete from student where s_no=" + Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value) + ";";
            //System.Diagnostics.Debug.Write(sqlStr);
            MySqlCommand mySqlCmd = new MySqlCommand(sqlStr,mySqlConn);
            mySqlCmd.ExecuteNonQuery();
            bind();
        }
        //gridview改变的时候设置每一行的id
        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int id = Convert.ToInt32(GridView1.DataKeys[GridView1.SelectedIndex].Value.ToString());
        }
        //获取事件
        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            //System.Diagnostics.Debug.Write(e.CommandName);
        }
        //更新
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            string ID = GridView1.DataKeys[e.RowIndex].Value.ToString();
            GridViewRow gvr = GridView1.Rows[e.RowIndex];
            string s_no = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[0].Controls[0])).Text.ToString().Trim();
            string s_name = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim();
            string s_age = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim();
            string s_sex = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim();

            string sql = "update student set s_no='" + s_no + "',s_name='" + s_name + "',s_age='" + s_age + "',s_sex='" + s_sex + "' where s_no=" + ID + ";";
            System.Diagnostics.Debug.Write(sql);
            MySqlCommand mySqlCmd = new MySqlCommand(sql, mySqlConn);
            mySqlCmd.ExecuteNonQuery();
            bind();
        }
        //取消
        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            bind();
        }
        //编辑
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            //int index = Convert.ToInt32(GridView1.DataKeys[e.NewEditIndex].Value);
            GridView1.EditIndex = e.NewEditIndex;
            bind();

        }
       

        //添加
        protected void Btn_add_Click(object sender, EventArgs e)
        {
            //Response.Redirect("WebForm2.aspx"); 跳转

            int sno = int.Parse(TextBox1.Text);
            int age = int.Parse(TextBox3.Text);

            string sql = "insert into student(s_no,s_name,s_age,s_sex) values('"+sno+"' ,'" + TextBox2.Text + "','" + age + "','" + TextBox4.Text + "');";
            //System.Diagnostics.Debug.Write(sql);
            MySqlCommand mySqlCmd = new MySqlCommand(sql, mySqlConn);
            mySqlCmd.ExecuteNonQuery();
            bind();

            TextBox1.Text = "";
            TextBox2.Text = "";
            TextBox3.Text = "";
            TextBox4.Text = "";
        }
    }
}


效果,

这个简单地界面中实现了增(Btn_add_Click),删(GridView1_RowDeleting),编辑(GridView1_RowUpdating GridView1_RowEditing GridView1_RowCancelingEdit);其中用到了5个事件,实现了删除和编辑。这些事件只需

要在GridView(界面)中注册然后在代码里实现就可以了,GridView的强大之处还在于它能适用于各种数据库!

觉得几点重要的地方:

1. bind()方法,实现了数据与GridView的绑定,之后主要起刷新作用

2. 在Page_Load()中调用bind()方法时必须加判断if (!IsPostBack),作用是看GridView中的数据是否发生改变

3. 在web项目中输出语句得用   System.Diagnostics.Debug.WriteLine();










原文地址:https://www.cnblogs.com/pangblog/p/3423997.html