ASP.NET DataTable等数据控件接受

http://blog.csdn.net/zhang_xinxiu/article/details/22372387

一、绑定控件之DataList


       该控件可以以自定义的格式显示各种数据源的字段,其显示数据的格式在创建的模板中定义,可以为项、交替项、选定项和编辑项创建模板。该控件也可以使用标题、脚注和分隔符模板自定义整体外观,还可以一行显示多个数据行。虽然DataList控件拥有很大的灵活性,但其本身不支持数据分页,编程者需要通过自己编写方法完成分页的功能。仅用于数据的显示,不支持编辑、插入、删除。
       优点:自定义格式显示数据、比较灵活。
       缺点:不支持分页,编辑插入。

   1、DataList简介


        上文说到DataList控件不仅能够灵活的显示数据,而且还支持编辑、插入、删除操作。想要显示数据基本的模板是必不可少的,相同的该控件也为开发人员提供了基本的模板使用。另外DataList不但提供了基本的ItemCommand事件,而且还封装了删除、取消、编辑、更新事件。通过将数据绑定到EditItemTemplate模板中能够容易的进入编辑状态,具体方法将会在下文中讲到。

        对于基本的模板和事件的使用方法上篇文章已经讨论,在此将不会深入的讨论。

二、控件使用技巧

 1、基本操作--增删改

      下面的代码示例使用Asp.NET实现,能够对数据进行增加、删除、修改。DataList控件封装了基本的删除和修改模板,但没有继承插入功能,示例中的插入使用的是Asp.Net的Literal控件来实现的,具体实现方法如下。
      删除页面:

    添加页面:

    编辑页面:


      前台代码:和Repeater控件基本用法相同,不同的是新增加了编辑模板,在编辑模板中绑定了数据,在进行编辑操作时只要跳转到编辑模板即可。代码中在基本模板ItemTemplate中添加了Literal控件,当点击添加按钮时再后台动态的添加新行,并在新行中添加数据控件。具体后台代码如下。

[html] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <div>  
  2.     <asp:DataList ID="DataList1" runat="server" OnItemCommand="DataList1_ItemCommand" OnCancelCommand="DataList1_CancelCommand" OnUpdateCommand="DataList1_UpdateCommand" OnEditCommand="DataList1_EditCommand" OnDeleteCommand="DataList1_DeleteCommand">  
  3.         <HeaderTemplate>  
  4.             <table border="1px" cellpadding="1px" cellspacing="5px" style="text-align:center;border-collapse:collapse;border-color:red;">  
  5.                 <tr style="background-color:yellow;">      
  6.                     <th>ID</th>  
  7.                     <th>内容</th>  
  8.                     <th>编辑</th>  
  9.                 </tr>  
  10.         </HeaderTemplate>  
  11.         <ItemTemplate>  
  12.             <tr onmouseover="backcolor=this.style.backgroundColor;this.style.backgroundColor='#6699ff'" onmouseout="this.style.backgroundColor=backcolor">  
  13.                 <td><%# Eval("id") %></td>  
  14.                 <td><%# Eval("name") %></td>  
  15.                 <td>  
  16.                     <asp:LinkButton ID="lbtDelete" runat="server" CommandName="Delete" CommandArgument='<%#Eval("id") %>'>删除</asp:LinkButton>  
  17.                     <asp:LinkButton ID="lbtEdit" runat="server" CommandName="Edit" CommandArgument='<%#Eval("name") %>'>编辑</asp:LinkButton>  
  18.                     <asp:LinkButton ID="lbtAdd" runat="server" CommandName="Add">添加</asp:LinkButton>  
  19.                 </td>  
  20.             </tr>  
  21.             <!--添加新行时动态添加文本框-->  
  22.             <asp:Literal ID="litAdd" runat="server"></asp:Literal>                
  23.         </ItemTemplate>  
  24.               
  25.         <EditItemTemplate>  
  26.             <tr>  
  27.                 <td>  
  28.                     <asp:TextBox ID="id" runat="server" Text='<%#Eval("id") %>'></asp:TextBox>  
  29.                 </td>  
  30.                 <td>  
  31.                     <asp:TextBox ID="name" runat="server" Text='<%#Eval("name") %>'></asp:TextBox>  
  32.                 </td>  
  33.                 <td>  
  34.                     <asp:LinkButton ID="lbtCancel" runat="server" Text="取消" CommandName="Cancel"></asp:LinkButton>  
  35.                     <asp:LinkButton ID="lbtUpdate" runat="server" Text="更新" CommandName="Update"  CommandArgument='<%#Eval("id") %>'></asp:LinkButton>  
  36.                 </td>  
  37.             </tr>  
  38.                   
  39.         </EditItemTemplate>  
  40.         <FooterTemplate>  
  41.             </table>  
  42.         </FooterTemplate>  
  43.     </asp:DataList>  
  44.   
  45.     <!--分页控件-->  
  46.     <div class="pageBar">  
  47.         <asp:Literal ID="lit" runat="server"></asp:Literal>  
  48.     </div>  
  49. </div>  

       后台代码:添加新行的操作是在ItemCommand事件中指定的,将新行的代码添加到Literal控件上实现了添加新行,并为新行指定控件。另外的基本编辑命令是在单独的事件中编写的,因为DataList为开发人员提供了基本的操作事件,如果想要进入某一个状态只需要将状态的ItemIndex值。

[csharp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     if (!Page.IsPostBack)  
  4.     {  
  5.         string strName = string.Empty;  //声明添加的内容  
  6.   
  7.         try  
  8.         {  
  9.             //获取需要添加的内容  
  10.             strName = Request.QueryString["name"].ToString();  
  11.         }  
  12.         catch  
  13.         {  
  14.   
  15.         }  
  16.   
  17.         //判断如果要添加的内容不为空将会进行添加操作  
  18.         if (strName!=string.Empty)  
  19.         {  
  20.             this.Insert(strName);  
  21.         }  
  22.   
  23.         //**********************************************************************  
  24.         //分页效果实现  
  25.         PagedDataSource pds = new PagedDataSource(); //声明分页类  
  26.         //设置分页属性  
  27.         pds.AllowPaging = true;  
  28.         pds.PageSize = 3;  
  29.         pds.DataSource = this.GetDT().DefaultView;  
  30.         pds.CurrentPageIndex = pageIndex - 1;  
  31.         //**********************************************************************  
  32.   
  33.         //绑定分页数据源  
  34.         this.DataList1.DataSource = pds;  
  35.         this.DataList1.DataBind();  
  36.     }  
  37. }  
  38.   
  39. /// <summary>  
  40. /// 添加新的数据行内容  
  41. /// </summary>  
  42. /// <param name="strName">获取要插入的内容</param>  
  43. private void Insert(string strName) {  
  44.     //向数据库中插入新内容  
  45.     using (SqlConnection con = this.GetSqlCon())  
  46.     {  
  47.         con.Open(); //打开数据库连接  
  48.         //设置命令对象  
  49.         SqlCommand sqlcom = new SqlCommand();  
  50.         sqlcom.Connection = con;  
  51.         sqlcom.CommandText = "insert match values(@name)";  
  52.         //添加参数  
  53.         sqlcom.Parameters.Add(new SqlParameter("@name", strName));  
  54.         //执行插入  
  55.         sqlcom.ExecuteNonQuery();  
  56.     }  
  57. }  
  58.   
  59. /// <summary>  
  60. /// 获取绑定的数据源  
  61. /// </summary>  
  62. /// <returns>DataTable,从match表中获取的内容</returns>  
  63. private DataTable GetDT()  
  64. {  
  65.     DataTable dt = new DataTable(); //声明数据库表  
  66.     //获取数据源  
  67.     using (SqlConnection con = this.GetSqlCon())  
  68.     {  
  69.         con.Open();  
  70.         //声明数据源命令  
  71.         SqlCommand sqlCom = new SqlCommand();  
  72.         sqlCom.CommandText = "select * from match";  
  73.         sqlCom.Connection = con;  
  74.         SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCom);  
  75.         SqlCommandBuilder sqlCb = new SqlCommandBuilder(sqlDa);  
  76.         sqlDa.Fill(dt);  
  77.     }  
  78.   
  79.     return dt;  
  80. }  
  81.   
  82. /// <summary>  
  83. /// 声明数据库链接对象  
  84. /// </summary>  
  85. /// <returns>SqlConnection,返回数据库连接对象</returns>  
  86. private SqlConnection GetSqlCon()  
  87. {  
  88.     SqlConnection sqlCon = new SqlConnection("server=.;database=myblog;uid=sa;pwd=1");  
  89.     return sqlCon;  
  90. }  
  91.   
  92. /// <summary>  
  93. /// 编辑命令事件  
  94. /// </summary>  
  95. /// <param name="source"></param>  
  96. /// <param name="e"></param>  
  97. protected void DataList1_EditCommand(object source, DataListCommandEventArgs e)  
  98. {  
  99.     this.DataList1.EditItemIndex = e.Item.ItemIndex;    //设置编辑的索引行  
  100.     //重新绑定数据源  
  101.     this.DataList1.DataSource = this.GetDT();  
  102.     this.DataList1.DataBind();  
  103. }  
  104.   
  105. /// <summary>  
  106. /// 删除命令事件  
  107. /// </summary>  
  108. /// <param name="source"></param>  
  109. /// <param name="e"></param>  
  110. protected void DataList1_DeleteCommand(object source, DataListCommandEventArgs e)  
  111. {  
  112.     if (e.CommandName == "Delete")  
  113.     {  
  114.         string id = e.CommandArgument.ToString();   //获取要删除行的id号  
  115.         //执行删除命令  
  116.         using (SqlConnection con = this.GetSqlCon())  
  117.         {  
  118.             con.Open();  
  119.   
  120.             SqlCommand sqlcom = new SqlCommand();  
  121.             sqlcom.Connection = con;  
  122.             sqlcom.CommandText = "delete from match where id=@id";  
  123.   
  124.             sqlcom.Parameters.Add(new SqlParameter("@id", id));  
  125.             sqlcom.ExecuteNonQuery();  
  126.         }  
  127.   
  128.         //重新绑定数据  
  129.         this.DataList1.DataSource = this.GetDT();  
  130.         this.DataList1.DataBind();  
  131.     }  
  132. }  
  133.   
  134. /// <summary>  
  135. /// 取消更新事件  
  136. /// </summary>  
  137. /// <param name="source"></param>  
  138. /// <param name="e"></param>  
  139. protected void DataList1_CancelCommand(object source, DataListCommandEventArgs e)  
  140. {  
  141.     if (e.CommandName == "Cancel")  
  142.     {  
  143.         this.DataList1.EditItemIndex = -1;  
  144.         //重新绑定数据  
  145.         this.DataList1.DataSource = this.GetDT();  
  146.         this.DataList1.DataBind();  
  147.     }  
  148. }  
  149.   
  150. /// <summary>  
  151. /// 更新按钮事件  
  152. /// </summary>  
  153. /// <param name="source"></param>  
  154. /// <param name="e"></param>  
  155. protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e)  
  156. {  
  157.     //判断如果是更新命令的话,将会执行更新命令  
  158.     if (e.CommandName == "Update")  
  159.     {  
  160.         int intId = int.Parse(e.CommandArgument.ToString()); //获取更新行的索引号  
  161.         string strname = ((TextBox)e.Item.FindControl("name")).Text;    //获取更新的内容  
  162.   
  163.         //更新数据库中的值  
  164.         using (SqlConnection sqlcon = this.GetSqlCon())  
  165.         {  
  166.             sqlcon.Open();  
  167.             SqlCommand sqlcom = new SqlCommand();  
  168.             sqlcom.CommandText = "update match set name=@name where id=@id";  
  169.             sqlcom.Connection = sqlcon;  
  170.   
  171.             SqlParameter[] sqlParam = new SqlParameter[] { new SqlParameter("@name", strname), new SqlParameter("@id", intId) };  
  172.             sqlcom.Parameters.AddRange(sqlParam);  
  173.   
  174.             sqlcom.ExecuteNonQuery();  
  175.   
  176.         }  
  177.         //更新完成后跳转页面  
  178.         this.DataList1.EditItemIndex = -1;  
  179.         //重新绑定数据  
  180.         this.DataList1.DataSource = this.GetDT();  
  181.         this.DataList1.DataBind();  
  182.   
  183.     }  
  184. }  
  185.   
  186. /// <summary>  
  187. /// 事件回发命令  
  188. /// </summary>  
  189. /// <param name="source"></param>  
  190. /// <param name="e"></param>  
  191. protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)  
  192. {  
  193.     //判断如果命令名称为Add,将会添加新行  
  194.     if (e.CommandName == "Add")  
  195.     {  
  196.         Literal lit = (Literal)e.Item.FindControl("litAdd");    //获取页面的对象  
  197.   
  198.         //向页面中添加新行标签  
  199.         StringBuilder strAdd = new StringBuilder("<tr><td><input type="text" id="45"></td><td><input type="text" id='name' onchange='InputKey()'></td>");  
  200.         strAdd.Append("<td><a href='Default.aspx' id='CancelInsert'>取消</a>");  
  201.         strAdd.Append("<a id='ok'>确认</a>");  
  202.         strAdd.Append("</td></tr>");  
  203.   
  204.         //将新行标签日俺家到html中  
  205.         lit.Text = strAdd.ToString();  
  206.     }  
  207. }  

 2、分页实现


      分页的实现效果和Repeater控件分页类似。在前台页面中添加Literal控件,并在后台使用PagedataSource类将数据进行分页。
      前台代码:在页面的最后添加了一个分页的div标记,并在div中添加了Literal控件,控件中标签的链接地址是在后台动态指定的。

[html] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <head runat="server">  
  2.     <title></title>  
  3.     <script src="Scripts/jquery-1.7.1.js"></script>  
  4.       
  5.     <script type="text/javascript" language="javascript">  
  6.   
  7.         $(function () {  
  8.             $("#ok").css("text-decoration", "underline").css("color", "blue");    
  9.             $("#CancelInsert").attr("href","Default.aspx");  
  10.         });  
  11.   
  12.         function InputKey() {  
  13.             var vartext = document.getElementById("name").value;  
  14.             $("#ok").attr("href","Default.aspx?name=" + vartext);         
  15.         }        
  16.     </script>  
  17.   
  18.     <style type="text/css">  
  19.         .pageBar {  
  20.             margin-top:50px;  
  21.         }  
  22.         .pageBar a{  
  23.             margin-top:50px;  
  24.             margin-left:20px;  
  25.             border-collapse:collapse;  
  26.             border:solid 1px black;  
  27.             background-color:#fbf9f9;  
  28.             padding:4px 4px 4px 4px;  
  29.         }  
  30.     </style>  
  31. </head>  
  32. <body>  
  33.     <form id="form1" runat="server">  
  34.           
  35.         <div>  
  36.             <!--分页控件-->  
  37.             <div class="pageBar">  
  38.                 <asp:Literal ID="lit" runat="server"></asp:Literal>  
  39.             </div>  
  40.         </div>  
  41.     </form>  
  42. </body>  
  43. </html>  


      后台代码:每次向后台请求数据都会重新为<a>标签指定链接页面的地址,这样能够使得PagedataSource能够链接到想要的页面。

[csharp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     if (!Page.IsPostBack)  
  4.     {  
  5.         int pageIndex = 1;  //声明页索引  
  6.         try  
  7.         {  
  8.             //获取要跳转页的索引号      
  9.             pageIndex = int.Parse(Request.QueryString["Page"].ToString());  
  10.             //如果是第零页,将会赋值为第一页  
  11.             if (pageIndex<0)  
  12.             {  
  13.                 pageIndex = 1;  
  14.             }  
  15.         }  
  16.         catch  
  17.         {  
  18.             //默认显示的是第一页  
  19.             pageIndex = 1;  
  20.         }  
  21.   
  22.         //判断如果要添加的内容不为空将会进行添加操作  
  23.         if (strName!=string.Empty)  
  24.         {  
  25.             this.Insert(strName);  
  26.         }  
  27.   
  28.         //**********************************************************************  
  29.         //分页效果实现  
  30.         PagedDataSource pds = new PagedDataSource(); //声明分页类  
  31.         //设置分页属性  
  32.         pds.AllowPaging = true;  
  33.         pds.PageSize = 3;  
  34.         pds.DataSource = this.GetDT().DefaultView;  
  35.         pds.CurrentPageIndex = pageIndex - 1;  
  36.         //**********************************************************************  
  37.   
  38.         //绑定分页数据源  
  39.         this.DataList1.DataSource = pds;  
  40.         this.DataList1.DataBind();  
  41.         //添加分页标签  
  42.         this.lit.Text = this.GetPageBar(pds);  
  43.     }  
  44. }  
  45. /// <summary>  
  46. /// 添加并设置分页命令  
  47. /// </summary>  
  48. /// <param name="pds">分页数据源</param>  
  49. /// <returns>包含分页连接的a标签</returns>  
  50. private string GetPageBar(PagedDataSource pds) {  
  51.     string Page = string.Empty;  
  52.     int intCurrent = pds.CurrentPageIndex + 1;  
  53.   
  54.     //设置首页链接地址  
  55.     if (intCurrent==1)  
  56.     {  
  57.         Page += "<a href="javascript:void(0)">首页</a>";// 转义字符:"为双引号  
  58.     }  
  59.     else  
  60.     {  
  61.         Page += "<a href="" + Request.CurrentExecutionFilePath + "?Page=1">首页</a>";  
  62.     }  
  63.   
  64.     //设置上一页链接地址  
  65.     if ((intCurrent-1)<1)  
  66.     {  
  67.         Page += "<a href="javascript:void(0)">上一页</a>";  
  68.     }  
  69.     else  
  70.     {  
  71.         Page += "<a href="" + Request.CurrentExecutionFilePath + "?Page=" + (intCurrent - 1) + "">上一页</a>";  
  72.     }  
  73.   
  74.     //设置下一页链接地址  
  75.     if ((intCurrent+1)>pds.PageCount)  
  76.     {  
  77.         Page +="<a href="javascript:void(0)">下一页</a>";  
  78.     }  
  79.     else  
  80.     {  
  81.             Page +="<a href=""+Request.CurrentExecutionFilePath +"?Page="+(intCurrent+1)+"">下一页</a>";     
  82.     }  
  83.   
  84.     //设置末页的链接  
  85.     if (intCurrent==pds.PageCount)  
  86.     {  
  87.         Page += "<a href="javascript:void(0)">末页</a>";  
  88.     }  
  89.     else  
  90.     {  
  91.         Page += "<a href="" + Request.CurrentExecutionFilePath + "?Page=" + pds.PageCount + "">末页</a>";  
  92.     }  
  93.   
  94.     return Page;    //返回也标签  
  95. }  

具体代码示例,请下载:DataList示例

三、对比升华

       结合前篇文章来对比下这两个数据绑定控件,对于Repeater控件它是微软开发的最基础的绑定控件只为开发人员提供了基本的事件流和基本的模板,各个子项完全可以由开发人员自己编写,而且不会生成冗余代码,唯一美中不足的是微软没封装向分页、编辑之类的功能,想要实现该功能必须自己编写了。

       相较Repeater控件,DataList控件不仅在Repeater基础上封装了编辑、删除、更新、取消之类的事件,而且还添加了Selectedtemplate模板,能够在后台代码中编写被选中行的显示效果,而且应用灵活,美中不足的是它也没有封装分页、插入的功能,只能由开发人员自己编写了,另外采用可视化窗口设计DataList样式后会生成冗余的代码,不便于阅读。

       总之在使用时它们两个各有利弊,如果只想绑定和显示数据那Repeater控件当然是我们的首选,当然如果有编辑、删除之类的操作,并想提前设计绑定样式的话不妨使用DataList。

结语

        

        对比两个控件它们都有优缺点,那是不是就没有较完美一些的绑定控件了呢?当然不是,.NET封装了多个数据绑定控件,上面的两种是在编程中经常用到的,真正功能齐全的是ListView控件,它的使用我们将会在下篇文章中着重讨论。

原文地址:https://www.cnblogs.com/jingxuan-li/p/6511614.html