GridView实现编辑,选择删除,分页功能

这篇博客介绍了如何在ASP.NET环境下使用GridView控件实现数据编辑、选择和删除功能,以及分页操作。作者通过创建student表并展示如何在前台代码中设置GridView属性,包括添加模板字段、绑定数据字段以及设置编辑、取消、更新事件。此外,还展示了如何添加全选和删除按钮,并在客户端添加确认提示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

初学ASP.NET不久自己动手做了个GridView简单的例子(感谢爱追逐的小猪、等等网络朋友)
VS2005下调试成功(个人感觉不错 遗憾的是界面不美观)。
主要目的是学习GridView控件。
表结构如下:
 --创建student表
create table student
(
stuID int identity(1,1) primary key,      --学号(只是为了方便)
stuName varchar(10) not null,           --姓名
stuSex varchar(2) not null,                  --性别
stuAge int ,                                             --年龄
stuAddress varchar(200)                    --家庭地址
)

default2.aspx前台代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>GridView使用例子</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        &nbsp;&nbsp;
        <asp:GridView ID="GridView1" DataKeyNames="stuID" runat="server" AllowPaging="True"
         AutoGenerateColumns="False"
         EmptyDataText="没有记录"
         OnRowEditing="GridView1_RowEditing"
         OnRowCancelingEdit="GridView1_RowCancelingEdit"
         OnRowUpdating="GridView1_RowUpdating"
         OnPageIndexChanging="GridView1_PageIndexChanging" OnRowDataBound="GridView1_RowDataBound"
          EditRowStyle-BackColor="#ebebeb">
            <Columns>
                <asp:TemplateField HeaderText="选择">
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" Text=" " Width="24px" Font-Size="10" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="stuID" HeaderText="学号" ItemStyle-Font-Size="10" ReadOnly="True"/>
               
                <asp:BoundField DataField="stuName" HeaderText="姓名" ItemStyle-Font-Size="10" ControlStyle-Width="50px"/>
               
                <asp:BoundField DataField="stuAge" HeaderText="年龄" ItemStyle-Font-Size="10" ControlStyle-Width ="20px" />
                <asp:TemplateField HeaderText="性别">
                    <ItemTemplate>
                         <asp:Label ID="Label1"  Font-Size ="10"  runat="server" Text='<%# Bind("stuSex", "{0}") %>' Width="56px"></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:RadioButtonList ID="RadioButtonList1"  Font-Size="10" runat="server" SelectedValue='<%# Bind("stuSex", "{0}") %>'>
                            <asp:ListItem>男</asp:ListItem>
                            <asp:ListItem>女</asp:ListItem>
                    </asp:RadioButtonList>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="stuAddress" HeaderText="地址" ItemStyle-Font-Size="10" />
                <asp:CommandField ShowEditButton="True" />
               
            </Columns>
           
            </asp:GridView>
              
        <asp:Button ID="Button1" runat="server" Text="全部选中" OnClick="Button1_Click" />
        <asp:Button ID="Button2" runat="server" Text="删除所选" OnClick="Button2_Click" OnClientClick="return confirm('真的要删除选中的项目吗?');" /><br />     
    </div>
    </form>
</body>
</html>

 

 

 

default2.aspx.cs后台代码如下:
using  System;
using  System.Data;
using  System.Configuration;
using  System.Collections;
using  System.Web;
using  System.Web.Security;
using  System.Web.UI;
using  System.Web.UI.WebControls;
using  System.Web.UI.WebControls.WebParts;
using  System.Web.UI.HtmlControls;
using  System.Data.SqlClient;
using  System.Drawing; //  要使用颜色,引入命名空间

public   partial   class  Default2 : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    
{       

        
if (!IsPostBack)
        
{
           BindGrid();
        }
      
    }


    
protected void BindGrid()
    
{
        
this.GridView1.DataSource =GetStudentData().Tables["student"];
        
this.GridView1.DataBind();
    }


    
private DataSet GetStudentData()
    
{
        
string strConn;
        
string strSql;
        strSql 
= "select *from student";
        strConn 
= "server=.;database=tempdb;uid=sa;pwd=;";
        SqlConnection conn 
= new SqlConnection(strConn);
        SqlDataAdapter myCommand 
= new SqlDataAdapter(strSql, conn);
        myCommand.SelectCommand.CommandType 
= CommandType.Text;
        DataSet myDataSet 
= new DataSet();
        myCommand.Fill(myDataSet, 
"student");
        conn.Close();
        
return myDataSet;
    }



    
//-------------------------------------------------------------------------------------
    
//项目全选或者取消全选
    protected void Button1_Click(object sender, EventArgs e)
    
{
        
if (this.Button1.Text == "全部选中")
        
{
            
foreach (GridViewRow row in GridView1.Rows)
            
{
                CheckBox box1
=(CheckBox)row.Cells[0].FindControl("CheckBox1");
                box1.Checked 
= true;
            }

            
            
this.Button1.Text ="全部取消";
            
        }

        
else
        
{
            
foreach (GridViewRow row in GridView1.Rows)
            
{
                CheckBox box1 
= (CheckBox)row.Cells[0].FindControl("CheckBox1");
                box1.Checked 
= false;
            }


            
this.Button1.Text = "全部选中";
        }


    }


    
//删除所选记录
    protected void Button2_Click(object sender, EventArgs e)
    
{      
            SqlConnection conn 
= new SqlConnection("server=.;database=tempdb;uid=sa;pwd=;");
            
foreach(GridViewRow row in GridView1.Rows)
            
{
                
                CheckBox box1 
= (CheckBox)row.Cells[0].FindControl("CheckBox1");
               
                
if (box1.Checked == true)
                


                    
string strCmd;
                    strCmd 
= "delete from student where stuID=" + Int64.Parse(row.Cells[1].Text);
                 

                    SqlCommand cmd 
= new SqlCommand(strCmd,conn);
                    cmd.CommandType 
= CommandType.Text;
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    conn.Close();                         
                }

           
            }

    
this.Button1.Text="全部选中";
           BindGrid();
      
    }

//------------------------------------------------------------------------------------------------------

 


//---------------------------------------------------------------------------------------------
//编辑选中的某行记录
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    
{
        
this.Button1.Text = "全部选中";
        GridView1.Columns[
0].Visible = false;
         GridView1.EditIndex
=(int)e.NewEditIndex; //设置要编辑的行
         BindGrid();
    }


    
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    
{
        
//string stuIdName = GridView1.DataKeyNames[0]; //获取主键名
        
//Response.Write(stuId);

        
int stuId = int.Parse(GridView1.Rows[e.RowIndex].Cells[1].Text);  //获取学生学号(主键),第二列,下标从0开始。
        string stuName = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text; //获取学生姓名
        int stuAge = int.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text);

        
//获取GridView表格中的数据
        
// 正常状态下((LiteralControl)GridView1.Rows[e.RowIndex].Cells[4].FindControl("Label1")).Text
        
//           
        
//编辑状态下((RadioButtonList)GridView1.Rows[e.RowIndex].Cells[4].FindControl("RadioButtonList1")).SelectedValue;
        
//          ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text; 
        string stuSex = ((RadioButtonList)GridView1.Rows[e.RowIndex].Cells[4].FindControl("RadioButtonList1")).SelectedValue;
        
string stuAddress = ((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text;
        
string strUpSql = "update student set stuname='" + stuName + "',stuAge=" + stuAge + ",stuSex='" + stuSex + "',stuAddress='" + stuAddress + "' where stuId=" + stuId;

        
string strConn;
        
string strSql;
        strConn 
= "server=.;database=tempdb;uid=sa;pwd=;";
        SqlConnection conn 
= new SqlConnection(strConn);
        SqlCommand myCommand 
= new SqlCommand(strUpSql, conn);
        myCommand.CommandType 
= CommandType.Text;
        conn.Open();
        myCommand.ExecuteNonQuery();
        conn.Close();
        conn.Dispose();
        GridView1.Columns[
0].Visible = true//显示选择列
        GridView1.EditIndex = -1;
        BindGrid();
    
    }


    
//取消更新
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    
{
        
this.Button1.Text = "全部选中";
        GridView1.Columns[
0].Visible = true//显示选择列
        GridView1.EditIndex = -1;
        BindGrid();

    }

//----------------------------------------------------------------------------------------------


//------------------------------------------
//分页功能
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    
{
        
this.Button1.Text = "全部选中";
        GridView1.PageIndex 
= e.NewPageIndex;
        
//Response.Write(GridView1.PageIndex); //显示当前页编号
        BindGrid();
      
    }

//------------------------------------

 

    
//鼠标变色事件
    
//此方法没有显示预期的效果,原因查找中

    
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    
{
        
if (e.Row.RowType == DataControlRowType.DataRow) //判断是否是DataRow,以防止鼠标经过Header也有效果
        {

            e.Row.Attributes.Add(
"onMouseover""c=this.style.backgroundcolor;this.style.backgroundcolor='#ff6699'");
            e.Row.Attributes.Add(
"onmouseout""this.style.backgroundcolor=c");

        }

    }


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值