datalist 中嵌套datalist 以及内層datalist 操作

来源:互联网 发布:人工蜂群算法 实例 编辑:程序博客网 时间:2024/05/17 03:52

找了好久 datalist 嵌套的例子,找到了地址2那个算是很好的了,在公司做了很久就是不能实现 内层datalist 删除事件,

回家认真从头做一遍,发现确实可以,下面是我的一个测试的简单例子,供大家参考吧

WebForm1.aspx

 <%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="doubleDatalist.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
  <title>WebForm1</title>
  <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
  <meta name="CODE_LANGUAGE" Content="C#">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
 </HEAD>
 <body MS_POSITIONING="GridLayout">
  <form id="Form1" method="post" runat="server">
   <table>
    <tr>
     <td>
      <asp:DataList id="dg1" runat="server">
       <ItemTemplate>
        <table>
         <tr>
          <td>
          <asp:TextBox ID="txtorderID1" Runat="server" Text='<%#DataBinder.Eval(Container, "DataItem.orderID")%>'>
                </asp:TextBox>
           
          </td>
         </tr>
         <tr>
          <td>
           <%#DataBinder.Eval(Container.DataItem,"ordertime")%>
          </td>
         </tr>
         <tr>
          <td>
           <asp:DataList id="Dg2" runat="server">
            <ItemTemplate>
             <table>
              <tr>
               <td>
                <asp:TextBox ID="txtorderID" Runat="server" Text='<%#DataBinder.Eval(Container, "DataItem.orderID")%>'>
                </asp:TextBox>
               </td>
               <td>
                <asp:TextBox ID="txtorderproductID" Runat="server" Text='<%#DataBinder.Eval(Container, "DataItem.orderproductID")%>'>
                </asp:TextBox>
               </td>
                <td >
                <asp:LinkButton ID="btnDel" Runat="server" CommandName="delete">删除</asp:LinkButton>
               </td>
              </tr>
              
             </table>
            </ItemTemplate>
           </asp:DataList>
          </td>
         </tr>
        </table>
       </ItemTemplate>
      </asp:DataList>
     </td>
    </tr>
   </table>
  </form>
 </body>
</HTML>

WebForm1.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.Data.SqlClient;

namespace doubleDatalist
{
 /// <summary>
 /// WebForm1 的摘要说明。
 /// </summary>
 public class WebForm1 : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.DataList dg1;
 
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
   BindDg1();
  }

  private void BindDg1()
  {
   SqlConnection myconn = new SqlConnection((string)System.Configuration.ConfigurationSettings.AppSettings["connStr"]);
   string SQL = "select * from orders ";
   DataSet ds = new DataSet();
   SqlDataAdapter adapter = new SqlDataAdapter(SQL,myconn);
   myconn.Open();
   adapter.Fill(ds,"orders");
   myconn.Close();
   this.dg1.DataSource = ds.Tables[0].DefaultView;
   this.dg1.DataBind();

  }

 

  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.dg1.ItemDataBound += new System.Web.UI.WebControls.DataListItemEventHandler(this.dg1_ItemDataBound);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  private void dg1_ItemDataBound(object sender, System.Web.UI.WebControls.DataListItemEventArgs e)
  {
   if ( e.Item.ItemType == ListItemType.EditItem || e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem )
   {
    DataList Dg2 = (DataList)e.Item.FindControl("Dg2");
    Dg2.ItemCommand += new DataListCommandEventHandler(Dg2_ItemCommand);
                TextBox  orderIDBox = (TextBox)e.Item.FindControl("txtorderID1");
    string orderID = orderIDBox.Text.ToString();
   

    Dg2.DataSource = GetSource(orderID).Tables[0];
                Dg2.DataBind();

   }
  }

  private DataSet GetSource(string orderID)
  {
   SqlConnection myconn = new SqlConnection((string)System.Configuration.ConfigurationSettings.AppSettings["connStr"]);
   string SQL = "select * from orderproduct where orderID = '"+orderID+"'";
   DataSet ds = new DataSet();
   SqlDataAdapter adapter = new SqlDataAdapter(SQL,myconn);
   myconn.Open();
   adapter.Fill(ds,"orders");
   myconn.Close();
   return ds;

  }

  private void Dg2_ItemCommand(object source, DataListCommandEventArgs e)
  {
   if (e.CommandName == "delete")
   {
    
    TextBox orderproductIDBox = (TextBox) e.Item.FindControl("txtorderproductID");
    int orderproductID = int.Parse(orderproductIDBox.Text.ToString());
    TextBox  orderIDBox = (TextBox)e.Item.FindControl("txtorderID");
    string orderID = orderIDBox.Text.ToString();

        SqlConnection myconn = new SqlConnection((string)System.Configuration.ConfigurationSettings.AppSettings["connStr"]);
    string SQL = "delete from orderproduct where orderID='"+orderID+"' and orderproductID = "+orderproductID;
    SqlCommand cmd = new SqlCommand(SQL,myconn);

    myconn.Open();
    cmd.ExecuteNonQuery();
    myconn.Close();
                
       BindDg1();
    
   }
  }


 }
}

下面是我的参考资料 地址2为主

地址1 :

http://www.microsoft.com/china/MSDN/library/data/dataAccess/NestGridHierData.mspx?mfr=true 

 

地址2 :

http://www.cnblogs.com/dongfangmn/archive/2005/11/11/273771.html

源码放在文件里面了,链接是
http://www.cnblogs.com/Files/dongfangmn/Modules.rar

对两层DataList的嵌套理解

    数据服务控件的嵌套最主要的是是内层控件数据的加载和事件的触发.下面以两层DataList为例介绍下实现的过程.效果如图:

 

注意

:内层控件数据绑定与事件声明在外层的ItemDataBind中实现;例子中外层DataList的Id为dlQuestion,内层为dlItem;代码如下

private void dlQuestion_ItemDataBound(object sender, System.Web.UI.WebControls.DataListItemEventArgs e)
        
{
            
            
if ( e.Item.ItemType == ListItemType.EditItem || e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem )
            
{
                LinkButton lb 
= (LinkButton)e.Item.FindControl("lbtnDelete");
                
if ( lb != null )
                    lb.Attributes.Add(
"onclick""return confirm('确实要删除么?')");
                 //得到内层DataList
                DataList dlItem
= (DataList)e.Item.FindControl("repItem");
                
if ( dlItem != null )
                
{
                    
if ( ViewState["repIndex"!= null )
                    
{
                       dlItem.EditItemIndex 
= (int ) ViewState["repIndex"];
                    }

                    dlItem .ItemCommand 
+= new DataListCommandEventHandler(dlItem_ItemCommand);

                    dlItem .ItemDataBound 
+= new DataListItemEventHandler(dlItem_ItemDataBound);


                    
int qid = ((InvQuestion)e.Item.DataItem).Que_Id;
                    ArrayList al 
= InvController.GetItemCollection( qid );
                    dlItem .DataSource 
= al;
                    dlItem .DataBind();
                }

                
            }

        
        }

其中ViewState对状态信息的读取和下面的保存联系后再讨论;

下面以内层DataList的Edit事件为例;

 

private void dlItem_ItemCommand(object source, DataListCommandEventArgs e)
        
{
            
if ( e.CommandName == "edit")
            
{
                
int qid = 0;
                
//得到外层datalist
                DataList dllist = (DataList)e.Item.Parent.Parent.Parent;
                                
//取得外层Question记录的Id
                HtmlInputHidden lbEditNum = (HtmlInputHidden)dllist.Items[0].FindControl("hidQuestion");
            
            
                
if ( lbEditNum.Value != "")
                
{
                    qid 
= int.Parse(lbEditNum.Value);
                }

                                
                                
//得到内层DataList
                DataList dl = (DataList)e.Item.Parent;
                dl.EditItemIndex 
= e.Item.ItemIndex;
                
//保存状态信息
                ViewState["repIndex"= e.Item.ItemIndex;
                
// Response.Write(e.Item.ItemIndex);

                                
//重新绑定内层DataList数据
                ArrayList al = InvController.GetItemCollection( qid );
                dl.DataSource 
= al;
                dl.DataBind();
            }

}

在内层DataList中e.CommandName="edit"事件中必须保存ViewState["index"] = e.Item.Index信息;否则在e.CommandName="update"中得不到editIndex的信息.需要保存ViewState的原因是:由于暂时没有找到更好的方法,内层DataList数据绑定需要在每个事件发生时对外层DataList重新绑定,也就是在Page.Load中加载DataBind()事件,对效率有一定影响

 

原创粉丝点击