欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.NET之GridView(2)【自定义】

程序员文章站 2022-07-02 18:35:17
 在(1)提到了如何不编写任何代码实现gridview对数据编辑、分页、删除等功能,但是这种操作存在很大的弊端———sql语句写在了h...
 在(1)提到了如何不编写任何代码实现gridview对数据编辑、分页、删除等功能,但是这种操作存在很大的弊端———sql语句写在了html页面。这样一来造成很大安全隐患,做出的程序很容易会被攻破。当然可以对语句进行,另一种就是让sql语句分离出来(这就用到了自定义gridview——通过编写一些代码来实现各项功能)
gridview控件6种常见类型的列:
示例:
.x界面:
 

<body>
    <form id="form1" runat="server">
    <p>
     
        <asp:gridview id="gridview1" runat="server" allowpaging="true" cellpadding="4"
            forecolor="#333333" gridlines="none"
            onpageindexchanging="gridview1_pageindexchanging1" pagesize="5"
            autogeneratecolumns="false"
            onrowcancelingedit="gridview1_rowcancelingedit"
            onrowdeleting="gridview1_rowdeleting" onrowediting="gridview1_rowediting"
            onrowupdating="gridview1_rowupdating">
            <alternatingrowstyle backcolor="white" />
            <columns>
                <asp:boundfield datafield="st_id" headertext="学号" />
                <asp:boundfield datafield="st_name" headertext="姓名" />
                <asp:boundfield datafield="st_gender" headertext="性别" />
                <asp:boundfield datafield="st_address" headertext="地址" />
                <asp:boundfield datafield="st_tel" headertext="联系电话" />
                <asp:boundfield datafield="st_nation" headertext="国家" />
                <asp:commandfield headertext="选择" showselectbutton="true" />
                <asp:commandfield buttontype="image" cancelimageurl="~/images/btncancel.gif"
                    editimageurl="~/images/btnupdate.gif" headertext="编辑" showeditbutton="true"
                    updateimageurl="~/images/btnsave.gif" />
                <asp:templatefield headertext="删除" showheader="false">
                    <itemtemplate>
                        <asp:imagebutton id="imagebutton1" runat="server" commandname="delete"
                            imageurl="~/images/btndelete.gif"
                            onclientclick="return confirm('确定删除吗?');" />
                    </itemtemplate>
                </asp:templatefield>
            </columns>
            <%--设置gridview样式,这里是套用内置的样式,在设置界面可以选择自动调用样式--%>
            <footerstyle backcolor="#990000" font-bold="true" forecolor="white" />
            <headerstyle backcolor="#990000" font-bold="true" forecolor="white" />
            <pagerstyle backcolor="#ffcc66" forecolor="#333333" horizontalalign="center" />
            <rowstyle backcolor="#fffbd6" forecolor="#333333" />
            <selectedrowstyle backcolor="#ffcc66" font-bold="true" forecolor="navy" />
            <sortedascendingcellstyle backcolor="#fdf5ac" />
            <sortedascendingheaderstyle backcolor="#4d0000" />
            <sorteddescendingcellstyle backcolor="#fcf6c0" />
            <sorteddescendingheaderstyle backcolor="#820000" />
        </asp:gridview>
     
    </p>
    </form>
</body>
.cs界面:
using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.ui;
using system.web.ui.webcontrols;
using system.data;
using system.data.sqlclient;
using system.configuration;
 
public partial class _default : system.web.ui.page
{
    protected void page_load(object sender, eventargs e)
    {
        if (!ispostback)
        {
            //调用自定义方法绑定数据到控件(为以后做mvc打下基础)
            binddata();
        }
    }
    private void binddata()
    {
        //这里将连接字符串写在web.config文件中,通过这个语句来调用,这样方便对连接字符串的修改
        string connstr = configurationmanager.connectionstrings["connstr"].connectionstring;
        //创建数据库连接对象
        sqlconnection con = new sqlconnection(connstr);
        //定义查询语句,这里最好将sql语句在sql中写好并验证正确确在复制粘贴过来(在对数据查询时最好只查所需的一些不需要的数据就不要取出,这样可以提高运行的效率)
        string sql = "select * from student";
        //创建适配器(自动打开关闭数据库)
        sqldataadapter dt = new sqldataadapter(sql, con);
        //创建数据集
        dataset ds = new dataset();
        //填充数据集
        dt.fill(ds);
        //设置gridview控件的数据源为定义的数据集ds
        gridview1.datasource = ds;
        //将数据表中的主键字段放置到gridview控件中的datakeynames属性中
        gridview1.datakeynames = new string[] { "st_id" };
        //绑定数据库表中数据
        gridview1.databind();
    }
 
    #region 用来执行sql语句
      /// <summary>
    /// 用来执行sql语句
    /// </summary>
    /// <param name="strsqlcom"></param>
    /// <returns></returns>
    public bool excesql(string strsqlcom)
    {
        //定义数据库连接字符串
        string strcon = configurationmanager.connectionstrings["connstr"].connectionstring;
        //创建数据库连接对象
        sqlconnection sqlcon = new sqlconnection(strcon);
        sqlcommand sqlcom = new sqlcommand(strsqlcom, sqlcon);
        try
        {
            //判断数据库是否为连连状态
            if (sqlcon.state == system.data.connectionstate.closed)
            { sqlcon.open(); }
            //执行sql语句
            sqlcom.executenonquery();
            //sql语句执行成功,返回true值
            return true;
        }
        catch
        {
            //sql语句执行失败,返回false值
            return false;
        }
        finally
        {
            //关闭数据库连接
            sqlcon.close();
        }
    }
    #endregion
   
 
  
    protected void gridview1_rowediting(object sender, gridviewediteventargs e)
    {
        //获取编辑行的索引
        gridview1.editindex = e.neweditindex;
        binddata();//数据绑定
    }
 
    #region 单击修改后所触发的事件
     /// <summary>
    /// 单击修改后所触发的事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gridview1_rowupdating(object sender, gridviewupdateeventargs e)
    {
        //取得编辑行的关键字段的值
        string st_id = gridview1.datakeys[e.rowindex].value.tostring();
        //取得文本框中输入的内容
        string st_name = ((textbox)(gridview1.rows[e.rowindex].cells[1].controls[0])).text.tostring().trim();
        string st_gender = ((textbox)(gridview1.rows[e.rowindex].cells[2].controls[0])).text.tostring().trim();
        string st_address = ((textbox)(gridview1.rows[e.rowindex].cells[3].controls[0])).text.tostring().trim();
        string st_tel = ((textbox)(gridview1.rows[e.rowindex].cells[4].controls[0])).text.tostring().trim();
        string st_nation = ((textbox)(gridview1.rows[e.rowindex].cells[5].controls[0])).text.tostring().trim();
        //定义更新操作的sql语句
        string update = "update student set st_name='" + st_name + "',st_gender='" + st_gender + "',st_address='" + st_address + "',st_tel='" + st_tel + "',st_nation='" + st_nation + "' where st_id='" + st_id + "'";
        bool b = excesql(update);//调用excesql执行更新操作
        if (b)
        {
            response.write("<script language=javascript>alert('修改成功!')</script>");
            //设置控件编辑项的索引值为—1 ,即取消编辑
            gridview1.editindex = -1;
            binddata();
        }
        else
        {
            response.write("<script language=javascript>alert('修改失败!')</script>");
        }
    }
    #endregion
    
    #region 点即取消按钮所触发的事件
    /// <summary>
    /// 点即取消按钮所触发的事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gridview1_rowcancelingedit(object sender, gridviewcancelediteventargs e)
    {
        //设置控件编辑项的索引值为—1 ,即取消编辑
        gridview1.editindex = -1;
        binddata();
    }
    #endregion
     
    #region 点击删除按钮时所触发的事件
    /// <summary>
    /// 点击删除按钮时所触发的事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// 
    protected void gridview1_rowdeleting(object sender, gridviewdeleteeventargs e)
    {
        string delete_sql = "delete from student where st_id='" + gridview1.datakeys[e.rowindex].value.tostring() + "'";
        bool delete = excesql(delete_sql);//调用excesql执行删除操作
        if (delete)
        {
            response.write("<script language=javascript>alert('删除成功!')</script>");
            binddata();//调用自定义方法重新绑定控件中数据
        }
        else
        {
            response.write("<script language=javascript>alert('删除失败!')</script>");
        }
    }
    #endregion
 
    #region 用来设置分页的事件
    /// <summary>
    /// 用来设置分页的事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gridview1_pageindexchanging1(object sender, gridviewpageeventargs e)
    {
        //获取当前分页索引值
        gridview1.pageindex = e.newpageindex;
        //重新绑定数据
        binddata();
    }
    #endregion
     
}

 

摘自 jory