首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

小弟才接触.net对联动不是很熟悉,使用XML做数据源的联动。无法给dropdownlist赋值!该如何处理

2012-01-01 
小弟才接触.net对联动不是很熟悉,使用XML做数据源的联动。无法给dropdownlist赋值!我使用的是网上的DropDow

小弟才接触.net对联动不是很熟悉,使用XML做数据源的联动。无法给dropdownlist赋值!


        我使用的是网上的DropDownList联动的例子(c#)   改写的。地区联动显示。
现在只有一个问题是,第二个DropDownList没有办法控制默认显示。


代码如下:前台
    <script   language= "javascript ">  

    var   Wantcount;  
    var   Groupcount;  

    Groupcount=0;

    Group   =   new   Array();  
    <asp:Literal   id= "Want "   runat= "server "> </asp:Literal>  

    function   changelocation1(locationid)  
    {  
      document.submit.DirectionList1.length   =   0;  
      var   locationid=locationid;  
      var   i;  
      var   flag;  
      var   j;  
      for   (i=0;i <Groupcount;   i++)  
      {  
        if   (Group[i][0]   ==   locationid)  
        {  
          flag   =   true;  
          for   (j   =0;j <document.submit.DirectionList1.length;j++)  
            if   (document.submit.DirectionList1[j].value   ==   Group[i][1])  
              {  
                flag   =   false;  
                break;  
              }  
          if   (flag)  
            document.submit.DirectionList1.options[document.submit.DirectionList1.length]  
            =   new   Option(Group[i][1],   Group[i][1]);  
        }  
      }  
    }  


    function   changelocation11(locationid,   direction)  
    {  

    }  

    </script>
    <body   id= "body_acc "   ms_positioning= "GridLayout ">
<form   id= "submit "   method= "post "   runat= "server ">
<table   width= "950 "   border= "0 "   align= "center "   cellpadding= "0 "   cellspacing= "0 "   id= "my ">
    <tr>
        <td   align= "center "   bgcolor= "333333 "> <!--#include   file= "bar.aspx "--> </td>
    </tr>
</table> <tr> <td   height=25     vAlign=bottom   bgcolor= "#FFFFFF "> 地区: </td>
    <td   bgcolor= "#FFFFFF "> <asp:dropdownlist   id= "SourceList1 "   runat= "server "   DataTextField= "v_source "   DataValueField= "v_source "   onchange= "changelocation1(document.submit.SourceList1.options[document.submit.SourceList1.selectedIndex].value);changelocation11(document.submit.SourceList1.options[document.submit.SourceList1.selectedIndex].value,document.submit.DirectionList1.options[document.submit.DirectionList1.selectedIndex].value) "   Width= "100px "> </asp:dropdownlist>


        <asp:dropdownlist   id= "DirectionList1 "   runat= "server "   DataValueField= "v_GroupName "   onchange= "changelocation11(document.submit.SourceList1.options[document.submit.SourceList1.selectedIndex].value,document.submit.DirectionList1.options[document.submit.DirectionList1.selectedIndex].value) "   Width= "100px "> </asp:dropdownlist> </td>
    </tr>
</table> </form>
<!--#include   file= "foot.aspx "-->
  <script   language= "javascript ">  
      changelocation1(document.submit.SourceList1.options[document.submit.SourceList1.selectedIndex].value);  
      changelocation11(document.submit.SourceList1.options[document.submit.SourceList1.selectedIndex].value,document.submit.DirectionList1.options[document.submit.DirectionList1.selectedIndex].value)  
    </script>  

后台:
                          DataSet   ds   =   new   DataSet();
                                ds.ReadXml(Server.MapPath( "DataSource.xml "));
                                for   (int   i   =   0;   i   <   ds.Tables[0].Rows.Count;   i++)
                                {
                                        DataRow   dr   =   ds.Tables[0].Rows[i];
                                        Want.Text   +=   String.Format( "Group[Groupcount++]   =   new   Array(\ "{0}\ ",\ "{1}\ ");\n ",   dr[ "v_Source "],   dr[ "v_GroupName "].ToString());
                                        if   (SourceList1.Items.FindByText(dr[ "v_Source "].ToString())   ==   null)
                                        {
                                                SourceList1.Items.Add(dr[ "v_Source "].ToString());
                                        }
                                }
      SourceList1.SelectedIndex   =   this.SourceList1.Items.IndexOf(this.SourceList1.Items.FindByValue( " "   +   dataReader[ "Type "].ToString()   +   " "));
DirectionList1.SelectedIndex   =   this.DirectionList1.Items.IndexOf(this.DirectionList1.Items.FindByValue( " "   +   dataReader[ "Type_H "].ToString()   +   " "));

现在问题是DirectionList1不能显示规定的默认值


------解决方案--------------------


2:定制联动下拉控件,必须的属性有USEDATA和Xml,USEDATA可以随便指定,应该是为了页面上有多个联动而设计的,现在没有支持,另一个xml属性用于指定xml格式数据源,因为1中要求xml格式固定所以根节点必须是TreeNodes, 子节点名是TreeNode 属性Desc/Value用于指定文本和值

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.ComponentModel;
using System.Collections.Specialized;

namespace Blackant.Controls
{
[DefaultProperty( "Value ")]
public class AssociatedDropDownList : WebControl, IPostBackDataHandler
{

#region 字段
private string _Xml= " <root/> ";
private XmlDocument _XmlDoc;

#endregion
#region 属性
[Bindable(true)]
[Category( "Appearance ")]
[DefaultValue( "0 ")]
[Localizable(true)]
public string Value
{
get
{
return ViewState[ "Value "] == null ? "0 " : ViewState[ "Value "].ToString();
}
set
{
ViewState[ "Value "] = value;

}
}

public string USEDATA
{
get
{
if (ViewState[ "USEDATA "] != null)
return ViewState[ "USEDATA "].ToString();
return String.Empty;
}
set { ViewState[ "USEDATA "] = value; }
}

/// <summary>
/// 字符串形式表达的xml格式文档
/// </summary>
public string Xml {
get { return _Xml; }
set { _Xml = value;

}
}
#endregion

#region 私有方法
int GetMaxLevel(XmlNode parent, int CurLevel)
{
int MaxLevel = CurLevel;
foreach (XmlNode xn in parent.ChildNodes)
{
if (xn.NodeType == XmlNodeType.Element)
{
int tmpLevel = GetMaxLevel(xn, CurLevel + 1);
MaxLevel = MaxLevel > tmpLevel ? MaxLevel : tmpLevel;
}
}
return MaxLevel;
}
#endregion
#region 重载事件

protected override void CreateChildControls()
{
_XmlDoc = new XmlDocument();
_XmlDoc.LoadXml(_Xml);

XmlElement root = _XmlDoc.DocumentElement;
int maxLevel = GetMaxLevel(root, 1);
for (int i = 1; i < maxLevel; i++)
{
DropDownList ddl = new DropDownList();
ddl.Attributes.Add( "USEDATA ", USEDATA);
ddl.Attributes.Add( "SUBCLASS ", i.ToString());
ddl.ID = ddl.ClientID;
Controls.Add(ddl);
}


base.CreateChildControls();
}

protected override void OnPreRender(EventArgs e)
{
Page.RegisterRequiresPostBack(this);
Page.ClientScript.RegisterHiddenField(this.ClientID, Value);
base.OnPreRender(e);
}
protected override void Render(HtmlTextWriter writer)
{


StringBuilder sb = new StringBuilder();
sb.AppendFormat( " <xml id=\ "{0}\ " style=\ "height:0px; width:0px; visibility:hidden;\ "> ", USEDATA);


sb.Append(_Xml);
sb.Append( " </xml> ");
sb.Append( "\r\n <script charset=\ "gb2312\ " type=\ "text/javascript\ " src=\ "/Script/prototype.js\ "> </script> \r\n ");
sb.Append( " <script charset=\ "gb2312\ " type=\ "text/javascript\ " src=\ "/Script/linkage.js\ "> </script> \r\n ");
sb.Append( " <script type= 'text/javascript '> ");
sb.AppendFormat( "var linkage = new Linkage(\ "{0}\ "); ", USEDATA);
sb.Append( "linkage.init(); ");
XmlNode xn = _XmlDoc.DocumentElement.SelectSingleNode( "//*[@Value= ' " + Value + " '] ");
List <string> init = new List <string> ();
if (xn != null)
{

while (xn != _XmlDoc.DocumentElement)
{
init.Insert(0, xn.Attributes[ "Value "].Value);
xn = xn.ParentNode;
}
}
for (int i = 0; i < init.Count; i++)
{
sb.AppendFormat( "linkage.initLinkage(\ "{0}\ ",\ "{1}\ ",{2}); ", USEDATA, init[i], i + 1);
}
sb.Append( "function SetAssociatedDropDownListValue(obj){var val=obj.value;while(val==\ "\ " && obj.previousSibling){obj=obj.previousSibling;val=obj.value;}$( ' "+ClientID+ " ').value=val;} ");
sb.Append( " </script> ");

Page.ClientScript.RegisterStartupScript(typeof(string), USEDATA, sb.ToString());



base.Render(writer);
}
#endregion


#region IPostBackDataHandler Members

//private static readonly object EventTextChanged = new object();

public virtual bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
//比较初始数据presentValue和回传数据postedValue
string postedValue = postCollection[postDataKey];
string presentValue = Value;
if (presentValue == null || postedValue != presentValue)
{
Value = postedValue;
return true;
}
return false;
}
void IPostBackDataHandler.RaisePostDataChangedEvent()
{

}


#endregion
}
}

[解决办法]
3,运行示例
<%@ Page Language= "C# " %>

<%@ Register Assembly= "Blackant.Controls " Namespace= "Blackant.Controls " TagPrefix= "bawc " %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN " "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

<script runat= "server ">

protected override void OnLoad(EventArgs e)
{

AssociatedDropDownList1.USEDATA = "test ";
AssociatedDropDownList1.Xml = @ "
<TreeNodes>
<TreeNode Desc= " "湖北省 " " Value= " "HB " ">
<TreeNode Desc= " "荆门市 " " Value= " "JM " "> </TreeNode>
<TreeNode Desc= " "武汉市 " " Value= " "WH " ">


<TreeNode Desc= " "汉口 " " Value= " "HK " "> </TreeNode>
<TreeNode Desc= " "武昌 " " Value= " "WC " "> </TreeNode>
</TreeNode>
</TreeNode>
<TreeNode Desc= " "北京市 " " Value= " "BJ " ">
</TreeNode>
</TreeNodes>

";

base.OnLoad(e);
}

protected void btnSubmit_Click(object sender, EventArgs e)
{
Response.Write( "当前选择: "+AssociatedDropDownList1.Value);
}
</script>

<html xmlns= "http://www.w3.org/1999/xhtml " >
<head runat= "server ">
<title> Untitled Page </title>
</head>
<body>
<form id= "form1 " runat= "server ">
<div>
<bawc:AssociatedDropDownList ID= "AssociatedDropDownList1 " runat= "server " />
<asp:Button runat= "Server " ID= "btnSubmit " Text= "查看回传数据 " OnClick= "btnSubmit_Click " />
</div>
</form>
</body>
</html>

热点排行