国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > 綜合 > 正文

如何在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環境下測試成功,程序執行結果如下:


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 西峡县| 进贤县| 平原县| 梧州市| 田阳县| 阿城市| 黄石市| 东辽县| 新津县| 崇左市| 石嘴山市| 明水县| 大埔县| 吉林市| 温泉县| 湖北省| 封开县| 东港市| 石景山区| 韩城市| 龙川县| 民勤县| 安庆市| 玉树县| 盈江县| 吉木萨尔县| 宁安市| 柳江县| 嘉义县| 永吉县| 齐齐哈尔市| 重庆市| 嘉定区| 怀来县| 巴彦淖尔市| 东宁县| 新密市| 嵩明县| 湘西| 阳高县| 诸暨市|