首页 > 开发 > 综合 > 正文

如何在DataGrid控件中实现编辑、删除、分类以及分页操作

2024-07-21 02:16:47
字体:
来源:转载
供稿:网友
如何在datagrid控件中实现编辑、删除、分类以及分页操作

文章出处:http://www.c-sharpcorner.com/asp/code/northwindlc.asp
前言:
这篇文章主要介绍如何在datagrid控件中实现编辑、删除、分类以及分页操作。为了实现我们的意图,我们使用sqlserver2000自带的northwind数据库。程序分为两部分:
1.包含html代码的.aspx文件
2.包含所有逻辑及方法的后台c#类文件
代码:
aspx文件:
在这里我们设计了一个datagrid对象,我为一些属性和方法作了注解。它就变得如此的简单:
    <asp:datagrid id="mydatagrid" style="z-index: 101; left: 16px; position: absolute; top: 104px" runat="server"
        borderstyle="ridge"
        gridlines="none"
        borderwidth="2px"
        bordercolor="white"
        backcolor="white"
        cellpadding="3"
        cellspacing="1"
        allowpaging="true"     // allowpaging属性的"true"时, 可进行分页操作
        allowsorting="true"      // 这是分类属性
        pagesize="15"       //设每页25条记录
        pagerstyle-mode="nextprev"      //有2种模式风格:next previous和page numberin
        pagerstyle-nextpagetext="next"
        pagerstyle-prevpagetext="previous"
        pagerstyle-horizontalalign="center"
        pagerstyle-position="topandbottom"
        datakeyfield="productid"       // datagrid的每条记录都包含一个productid字段
        onpageindexchanged="mydatagrid_pageindexchanged"    // 当用户进行翻页操作时就激活mydatagrid_pageindexchanged函数(function)
        onsortcommand="sort_grid"                           //当用户对datagrid分类时激活sort_grid(function)函数
        ondeletecommand="mydatagrid_delete"                 //这一事件激活mydatagrid_delete函数(function)删除一条记录
        onupdatecommand="mydatagrid_update"                 //这一事件激活mydatagrid_update函数(function)更新一条记录
        oncancelcommand="mydatagrid_cancel                  //这一事件激活mydatagrid_cancel函数(function)取消当前操作
        oneditcommand="mydatagrid_edit"                     //这一事件激活mydatagrid_edit函数(function)编辑一条记录
        autogeneratecolumns="false"                         // 设置自动产生行为"false"
        horizontalalign="left">
        <footerstyle forecolor= "black"backcolor="#c6c3c6"></footerstyle>
        <headerstyle font-bold= "true" forecolor= "#e7e7ff"backcolor="#4a3c8c"></headerstyle>
        <pagerstyle nextpagetext="next" prevpagetext="previous" horizontalalign="right" forecolor="black"  
                            position= "topandbottom"backcolor="#c6c3c6"></pagerstyle>
        <selecteditemstyle font-bold= "true" forecolor= "white"backcolor="#9471de"></selecteditemstyle>
        <itemstyle forecolor= "black"backcolor="#dedfde"></itemstyle>

   <columns>
     <asp:editcommandcolumn buttontype="linkbutton" updatetext= "<img border=0 src=http://www.163design.net/n/a/ok.gif>" canceltext= "<imgborder=0 src=http://www.163design.net/n/a/cancel.gif>" edittext= "<imgborder=0src=http://www.163design.net/n/a/edit.gif>"></asp:editcommandcolumn>
     <asp:buttoncolumn text= "<img border= 0src= delete.gif>"commandname="delete"></asp:buttoncolumn>
     <asp:boundcolumn datafield= "productid" sortexpression="productid" readonly="true" headertext= "productid"></asp:boundcolumn>
     <asp:boundcolumn datafield= "productname" sortexpression="productname" headertext= "productname"></asp:boundcolumn>
     <asp:boundcolumn datafield="quantityperunit" sortexpression="quantityperunit" headertext= "quantity perunit"></asp:boundcolumn>
     <asp:boundcolumn datafield="unitprice" sortexpression="unitprice" headertext= "unit price"dataformatstring="{0:c}"></asp:boundcolumn>
     <asp:boundcolumn datafield="unitsinstock" sortexpression="unitsinstock" headertext= "units instock"></asp:boundcolumn>
     <asp:boundcolumn datafield="unitsonorder" sortexpression="unitsonorder" headertext= "units onorder"></asp:boundcolumn>
     <asp:boundcolumn datafield= "reorderlevel" sortexpression="reorderlevel" headertext= "reorderlevel"></asp:boundcolumn>
     <asp:templatecolumn headertext="discontinued" sortexpression="discontinued">
      <itemtemplate>
       <asp:checkbox id= "discontinued" runat="server" checked= '<%# databinder.eval(container.dataitem, "discontinued")%>' />
      </itemtemplate>
     </asp:templatecolumn>
    </columns>
</asp:datagrid>
你看,是不是不难?关键在于我们常动手动脑。多看资料也很关键哦!
c#后台程序:
让我们先看一段程序:
   private void page_load(object sender, system.eventargs e)
   {
       if(!ispostback)
       {
            bindgrid();
       }
   }
上面展现的是一种非常好的技术,当页面不是postback状态时,就绑定数据。这意味着,一旦页面被请求数据将被绑定。
继续看程序:
/// <summary>
      /// 这个函数返回关于产品细节的dataset
  /// </summary>
  ///<returns></returns>
  private dataset getproductdata()
  {
   ///sqlstatement是一个sql语句(string型的)
   string sqlstatement="select  products.productid, products.productname, products.quantityperunit, products.unitprice, "+
                      "products.unitsinstock, products.unitsonorder, products.reorderlevel, products.discontinued "+
       "from  products"; :
   ///声明 sqlconnection对象:myconnection
  sqlconnection myconnection=new sqlconnection(@"server=(local)/netsdk;”+
”database=northwind;uid=northwind;pwd=northwind;");
///声明command对象:mycommand
   sqldataadapter mycommand = new sqldataadapter(sqlstatement,myconnection);
///设置command命令的类型为text类型
   mycommand.selectcommand.commandtype=commandtype.text;
   ///创建dataset对象实例
   mydataset = new dataset();
   ///把从表products返回的数据填充mydata
   mycommand.fill(mydataset, "products");
   ///最后返回mydataset对象
   return mydataset;
  }
这段代码执行给定的sql语句访问数据库,私有函数getproductdata返回一个包含数据记录的dataset。下一步,让我们看如何编辑记录:
/// <summary>
     /// 这个函数只有当用户点击edit按钮时才会被激活
  /// </summary>
  /// <paramname="sender"></param>
  /// <paramname="e"></param>
  protected void mydatagrid_edit(object sender, datagridcommandeventargs e)
  {
     ///找出被选定项目的索引(itemindex),并且进一步绑定数据
     mydatagrid.edititemindex = (int)e.item.itemindex;
     bindgrid();
  }
通过上面代码所附带的注解大家也能明白mydatagrid_edit函数的功能:当用户点击edit按钮时激活mydatagrid_edit函数,并且程序找到所要编辑的记录的索引,把该索引号分配给datagrid的edititemindex属性。
如果用户点击cancel按钮,将调用我们在上面的.aspx文件中提到的mydatagrid_cancel函数,程序如果分配给datagrid属性 edititemindex的值为-1,就意味着用户没有选择edit,程序如下:
/// <summary>
     /// 用户点击cancel按钮时激活mydatagrid函数
  /// </summary>
  /// <paramname="sender"></param>
  /// <paramname="e"></param>
  protected void mydatagrid_cancel(object sender, datagridcommandeventargs e)
  {
      mydatagrid.edititemindex = -1;
      bindgrid();
  }
下面的代码像我们展现了如何从datagrid中删除一条选中的记录。我们知道web控件datagrid有一datakeyfield属性,事实上它就包含了每条记录的productid字段值。您一定会问如何通过datakeyfield属性得到datagrid中选中记录的productid值呢?下面这段代码会让您释然的:
-----
int productid =(int)mydatagrid.datakeys[(int)e.item.itemindex];
-----
mydatagrid_delete函数代码如下:
        /// <summary>
        ///从dataset中删除一条记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void mydatagrid_delete(object sender, datagridcommandeventargs e)
{
            int productid =(int)mydatagrid.datakeys[(int)e.item.itemindex];
            string sqlstatement="delete products where productid="+productid;
            string myconnectionstring = "server=localhost;uid=sa;pwd=;database=northwind";

            sqlconnection myconnection = new sqlconnection(myconnectionstring);
            sqlcommand mycommand = new sqlcommand (sqlstatement,myconnection);            
            
            mycommand.commandtimeout = 15;
            mycommand.commandtype=commandtype.text;

            try
            {
                myconnection.open();
                mycommand.executenonquery();
                myconnection.close();
            }
            catch(exception ee)
            {
                throw ee;
            }
            mydatagrid.edititemindex = -1;
            bindgrid();                
    }
下面的代码用来更新northwind数据库的产品信息,
我们可以使用下面这项技术检索值:
-------------------
bool discon=((checkbox)e.item.findcontrol("discontinued")).checked;
-------------------
这时我们使用fincontrol()方法就能得到discontinued checkbox的值.
        /// <summary>
        ///更新记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void mydatagrid_update(object sender, datagridcommandeventargs e)
        {
            int productid =(int)mydatagrid.datakeys[(int)e.item.itemindex];
            string productname = ((textbox)e.item.cells[3].controls[0]).text;
            string quantityperunit=((textbox)e.item.cells[4].controls[0]).text;
            string unitprice = ((textbox)e.item.cells[5].controls[0]).text;
            int16 unitsinstock=int16.parse(((textbox)e.item.cells[6].controls[0]).text);
            int16 unitsonorder=int16.parse(((textbox)e.item.cells[7].controls[0]).text);
            int16 reorderlevel=int16.parse(((textbox)e.item.cells[8].controls[0]).text);
            bool discon=((checkbox)e.item.findcontrol("discontinued")).checked;
            int result;

            if(!discon)
            {
                result=0;
            }
            else
            {
                result=1;
            }
            string sqlstatement="update    products "+
                "set  productname='"+productname+"', "+
                "quantityperunit='"+quantityperunit+"', "+
                "unitprice ="+unitprice.substring(unitprice.indexof("¥")+1)+", "+
                "unitsinstock ="+unitsinstock+", "+
                "unitsonorder ="+unitsonorder+", "+
                "reorderlevel ="+reorderlevel+", "+
                "discontinued ="+result+
                " where     productid ="+productid;

                string myconnectionstring = "server=localhost;uid=xjb;pwd=xjb;database=northwind";
            sqlconnection myconnection = new sqlconnection(myconnectionstring);
            sqlcommand mycommand = new sqlcommand(sqlstatement,myconnection);            
            
            mycommand.commandtimeout = 15;
            mycommand.commandtype = commandtype.text;        

            try
            {
                myconnection.open();
                mycommand.executenonquery();
                myconnection.close();
            }
            catch(exception ee)
            {
                throw ee ;
            }

            mydatagrid.edititemindex = -1;
            bindgrid();
        }

接下来的bindgrid()调用私有函数getproductdata取得dataset对象并绑定到datagrid控件。
/// <summary>
/// 接受数据库数据并再次绑定
/// </summary>
  protected void bindgrid()
  {
   mydatagrid.datasource=getproductdata().tables["products"].defaultview;
   mydatagrid.databind();
  }
用户在datagrid中向前或向后移动时激活mydatagrid_pageindexchanged事件,因为datagrid 不能自动的获取新页的索引号,所以我们只能手动取得索引号。
        /// <summary>
        /// 分页操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void mydatagrid_pageindexchanged(object source, datagridpagechangedeventargs e)
        {
            mydatagrid.currentpageindex=e.newpageindex;
            bindgrid();
        }
     用户在任何时候想对数据分类时,就激活下面的sort_grid事件。例如,如果用户点击field headers,事件就将被激活,并且把数据分成我们想要的分类。 我们需要dataview对象去为e.sortexpression.tostring()方法分类,返回的是被点击域标题的分类。
/// <summary>
/// 分类
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void sort_grid(object sender, datagridsortcommandeventargs e)
{
    
    dataview dv= new dataview(getproductdata().tables["products"]);
    dv.sort= e.sortexpression.tostring();
    mydatagrid.datasource=dv;
    mydatagrid.databind();            
}
执行结果:
该程序在win2000+sqlserver2000+vs.netbeta2环境下测试成功,程序执行结果如下:


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表