Ajax扩展控件

 

6.AutoCompleteExtender(自动补全控件)

 

http://www.cnblogs.com/abcdwxc/archive/2007/10/29/941260.html

http://www.cnblogs.com/gaolei/archive/2009/01/01/1366520.html

http://blog.csdn.net/bosnma/archive/2009/02/06/3866911.aspx

类似于谷歌百度等搜索的自动补全的功能,可以辅助TextBox控件自动输入。

HTML:

  <asp:TextBox ID="TextBox1" runat="server" Width="300"></asp:TextBox>

  <ajax:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender" runat="server"       

ServicePath="AutoComplete.asmx" ServiceMethod="GetWordList" TargetControlID="TextBox1"       

MinimumPrefixLength="1" CompletionSetCount="20" CompletionInterval="1000" BehaviorID="AutoCompleteEx"       

CompletionListCssClass="autocomplete_completionListElement"       

CompletionListItemCssClass="autocomplete_listItem" EnableCaching="true"       

CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem" DelimiterCharacters=";,:">
   <Animations>
    <OnShow>
     <Sequence>
      <%-- Make the completion list transparent and then show it --%>
      <OpacityAction Opacity="0" />
      <HideAction Visible="true" />                       
      <%--Cache the original size of the completion list the first time
          the animation is played and then set it to zero --%>                           
      <ScriptAction Script="// Cache the size and setup the initial size
         var behavior = $find('AutoCompleteEx');
         if (!behavior._height) {
         var target = behavior.get_completionList();
         behavior._height = target.offsetHeight - 2;
         target.style.height = '0px';
         }" />                        
      <%-- Expand from 0px to the appropriate size while fading in --%>                          
      <Parallel Duration=".4">
       <FadeIn />
       <Length PropertyKey="height" StartValue="0" EndValueScript="$find('AutoCompleteEx')._height" />
      </Parallel>
     </Sequence>
    </OnShow>
    <OnHide>
      <%-- Collapse down to 0px and fade out --%>      
      <Parallel Duration=".4">
       <FadeOut />
       <Length PropertyKey="height" StartValueScript="$find('AutoCompleteEx')._height" EndValue="0" />
      </Parallel>
    </OnHide>
   </Animations>
</ajax:AutoCompleteExtender>

 

主要属性:

      TargetControlID:指定将被辅助完成自动输入的控件ID,这里的控件只能是TextBox;

  ServicePath:指出提供服务的WEB服务路径,若不指出则ServiceMethod表示本页面对应的方法名;

  ServiceMethod:指出提供服务的方法名;

  MinimumPrefixLength:指出开始提供提示服务时,TextBox控件应有的最小字符数,默认为3;

  CompletionSetCount:显示的条数,默认为10;

  EnableCaching:是否在客户端缓存数据,默认为true;

  CompletionInterval:从服务器读取数据的时间间隔,默认为1000,单位:毫秒。 

      CompletionListCssClass:补全框的样式

      CompletionListItemCssClass:补全框选项的样式

      CompletionListHighlightedItemCssClass:补全框被选中项的样式

      Animations:给补全框添加动画

 

WebServer大体内容:

   [System.Web.Script.Services.ScriptService] //由于Ajax实际上是也是通过javascript调用该web服务,所以要去//掉此处的注释

    public class AutoComplete1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string[] GetWordList(string prefixText, int count)
        {
            List<string> list = new List<string>();  //using System.Collections.Generic;
            for (int i = 0; i < 20; i++)
            {
                list.Add(prefixText + i.ToString());
            }
            return list.ToArray(); //List<T>的ToArray()方法将list里的元素复制到T类型的数组中,并返回该数组
        }
    }

 

重要提示:

[WebMethod]方法的返回类型必需为:string [];传入参数类型必需为:string,int;两个传入参数名必需为:prefixText,count

第一个参数就是用户录入的内容, 第二个参数是定义中指定的下拉列表长度,也就是要返回的项的个数,默认长度10 

CSS:

        ul, li

       {

margin:0;

padding:0;

border:none;

       }

      /*兼容IE8*/

        body 

       {

margin:0;

padding:0;

border:none;

       }

   /*AutoComplete flyout */

   .autocomplete_completionListElement 

      {  

visibility : hidden;

margin : 0px!important;

background-color : inherit;

color : windowtext;

border : buttonshadow;

border-width : 1px;

border-style : solid;

cursor : 'default';

overflow : auto;

height : 200px;

        text-align : left; 

        list-style-type : none;

      }

   /* AutoComplete highlighted item */

  .autocomplete_highlightedListItem

     {

background-color: #ffff99;

color: black;

padding: 1px;

     }

   /* AutoComplete item */

 

    .autocomplete_listItem 

     {

background-color : window;

color : windowtext;

padding : 1px;

     }

重要提示:  

由于补全框最终是由ul,li布局的,在css里要设置成 ul, li{margin:0;padding:0;border:none;}才能正常显示,另外对于IE浏览器还要加上body{margin:0;padding:0;border:none;}才能正常显示

 

补:直接在js中给控件定义客户端事件(如定义button1的客户端单击事件)

  window.οnlοad=function(){

   $get("button1").οnclick=function(){alert("直接在js中给控件定义客户端事件")};

  };  //$get()为Microsoft Ajax Labrary里的函数

还记得在讲AnimationExtender(动画控件)时Button控件的OnClientClick吗?如果Button有服务端事件的话,OnClientClick可以决定是否执行该服务端事件,这主要与返回值是true还是false有关。由于在同一个Button中只能声明一个onclick事件,在这里我们可以在js中给Button定义客户端事件onclick,在html里定义一个服务端事件onclick(这俩onclick并不冲突),由于在客户端触发同一控件的相同事件时先执行客户端事件(除页面载入事件),所以可以让js中定义客户端事件的函数的返回值为true或false来达到相同效果。

  http://msdn.microsoft.com/zh-cn/magazine/cc163300.aspx(了解Microsoft Ajax Labrary)

  在讲AnimationExtender(动画控件)时提到过Microsoft Ajax Labrary微软自己的javascript框架,但要注意想想我们在使用jQuery时要先引入jQuery.js等,同样如果我们要使用Microsoft Ajax Labrary时,我们的javascript代码要写在

<asp:ScriptManager ID="ScriptManager1" runat="server"/>后面或在下载microsoftajax.js后

<script type="text/javascript" src="microsoftajax.js"></script>(显式引入microsoftajax.js,这是ScriptManager的工作之一)。微软给出的Ajax扩展控件之一AlwaysVisibleContral控件的例子中的时间格式化函数localeFormat()也是Microsoft Ajax Labrary里的函数。

 

 

AutoCompleteExtender补全数据库里的数据的例子

http://www.cnblogs.com/fightLonely/archive/2010/04/13/1710943.html

http://moosdau.blog.163.com/blog/static/4371128200852524114408/(自定义参数(contextKey))

http://topic.csdn.net/u/20071026/14/3be725db-1643-435e-b142-46410df801f9.html

http://topic.csdn.net/u/20090223/09/855aa1be-02d7-4bdb-968d-382cf666c261.html

通过下拉列表框的选项来决定执行哪个SQL语句,从而为web服务提供相应数据从而进行不同的自动补全(主要涉及到如何为

public string[] GetWordList(string prefixText, int count,string contextKey){}的contextKey传值的问题(这是又一种重载,其中contextKey参数对应AutoCompleteExtender控件的contextKey属性值,count参数对应AutoCompleteExtender控件的CompletionSetCount属性值))

 

HTML:

 <asp:ScriptManager ID="ScriptManager1" runat="server">

 </asp:ScriptManager>
 //下面的js代码是关键,主要作用是在文本框里按下键时根据下拉列表框的选项决定contextKey属性的值
 <script type="text/javascript">
    function setcontextKey()
    {
     var ddlist=document.getElementById("<%=DropDownList1.ClientID %>");
 //此处用$find(关于$find与$get的区别请看第四个链接),另第二个链接有误,$find()里的id应为AutoCompleteExtender控 
//件的BehaviorID(可以看出用js在页面找AutoCompleteExtender都是用其BehaviorID)而非ID
     var AutoComp=$find("AutoCompleteEx");
 //AutoCompleteExtender的set_contextKey方法
         AutoComp.set_contextKey(ddlist.options[ddlist.selectedIndex].value);
    }
 <asp:DropDownList ID="DropDownList1" runat="server"> //按标题自动补全还是按内容自动补全
   <asp:ListItem Selected="True">标题</asp:ListItem>
   <asp:ListItem>内容</asp:ListItem>
 </asp:DropDownList>
 <asp:TextBox ID="TextBox1" runat="server" Width="300" οnkeydοwn="setcontextKey()"></asp:TextBox>
  <ajax:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender" runat="server"    
ServicePath="AutoComplete.asmx" ServiceMethod="GetWordList" TargetControlID="TextBox1"    
MinimumPrefixLength="1" CompletionSetCount="8" CompletionInterval="1000" BehaviorID="AutoCompleteEx"    
CompletionListCssClass="autocomplete_completionListElement"    
CompletionListItemCssClass="autocomplete_listItem" EnableCaching="true"    
CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem" DelimiterCharacters=";,:"    ContextKey="">
 <Animations>
  ....
 </Animations>
</ajax:AutoCompleteExtender>

WebService大体内容:

 

 [System.Web.Script.Services.ScriptService]
    public class AutoComplete1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string[] GetWordList(string prefixText, int count,string contextKey)
        {
            if (contextKey == "标题")
            {
                List<string> list = new List<string>();
                SqlConnection myCon = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial 
Catalog=newsystem;Integrated Security=True");
                myCon.Open();
                SqlCommand myCmd = new SqlCommand("select top " + count+ " title from News where title like 
'" + prefixText + "%'group by title order by title ", myCon);
                SqlDataReader myDR = myCmd.ExecuteReader();
                while (myDR.Read())
               {
                  list.Add(myDR["title"].ToString().Trim()); //会有选项后面有空格的情况,用Trim去掉
               }
                myCon.Close();
                 return list.ToArray();
               }
            else if (contextKey == "内容")
            {
                List<string> list = new List<string>();
                SqlConnection myCon = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial 

Catalog=newsystem;Integrated Security=True");
                myCon.Open();
                SqlCommand myCmd = new SqlCommand("select top " + count + " title from News where content 

like '%" + prefixText + "%'group by title order by title ", myCon);
                SqlDataReader myDR = myCmd.ExecuteReader();
                while (myDR.Read())
                {
                    list.Add(myDR["title"].ToString().Trim());
                }
                myCon.Close();
                return list.ToArray();
            }
            else  //if...else if...else语句位于有返回值的函数里要加上最后一个else,因为编译器会试图让你的前面 

                 //的if()...else if()为false,这样就不会有返回值了,所以此处随便写以else
            {
                string[] strs=new string[]{"1","2"};
                return strs;
            }
        }
    }

 在选项不多的情况下,补全框背景不很很好看,可以直接设成白色:

.autocomplete_completionListElement{background-color:White;}

 

 

 

7.CalendarExtender(日历控件)

 

Ajax日历控件能够与文本框控件关联,当在可跳出的日历控件中选中一个日期后该日期会以一定格式的文本显示在文本框里。

HTML:

    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />

    <ajax:CalendarExtender ID="TextBox1_CalendarExtender" runat="server" 

     Enabled="True" TargetControlID="TextBox1">

    </ajax:CalendarExtender>

这样简单的设置基本就可以实现上述功能了,但你会发现弹出的日历控件里的文字是英文的,要改成中文的话就涉及到浏览器

的首选语言的选择了(在IE浏览器中设置:工具-Internet选项-语言|在Chrome中设置:钳子图标-选项-高级设置-更改字体和语言设置|常用语言:中文(中国)[zh-CN],英语(美国)[en-US],英语(英国)[en-GB],中文(台湾)[zh-TW],西班牙语(国际)[es-ES],日语[ja-JP]),我们也可以在在 Page 标签里添加Culture="auto" UICulture="auto"(如果是在web.config里是这样设置:<system.web><globalization uiCulture="auto" culture="auto" /></system.web>)这样那些运用了本地化技术的控件就能够获取首选语言从而决定显示哪种语言了,我们也可以在代码里直接指定首选语言Culture="zh-CN" UICulture="zh-CN"。

在这里要让日历控件获取到首选语言的方法是给ScriptManager控件添加俩属性EnableScriptGlobalization="true" 

EnableScriptLocalization="true",这样设置后日历控件里的文字就变成中文的了。

 

HTML:

     <asp:ScriptManager ID="ScriptManager1" runat="server" EnableScriptGlobalization="true"       

EnableScriptLocalization="true"></asp:ScriptManager>

     <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />

     <asp:Label ID="Label1" runat="server" Text="弹出日历"></asp:Label>

     <ajax:CalendarExtender ID="TextBox1_CalendarExtender" runat="server" 

        Enabled="True" TargetControlID="TextBox1" PopupPosition="Left" Format="yyyy|MM|dd"

         CssClass="MyCalendar" SelectedDate="6,20,1991" PopupButtonID="Label1">

     </ajax:CalendarExtender>   

 

仅几个属性需要说明一下:SelectedDate(默认文本框显示的日期,注意格式)PopupButtonID(点击就会弹出日历的控件的ID,不一定非要是按钮控件,默认当文本框得到焦点就会弹出日历,如果设置了此属性,则其获焦点不会弹出日历)

 

CSS:

    .MyCalendar .ajax__calendar_container {

    border:1px solid #646464;

    background-color: lemonchiffon;

    color: red;}

    .MyCalendar .ajax__calendar_other .ajax__calendar_day,

    .MyCalendar .ajax__calendar_other .ajax__calendar_year {

    color: black;

    }

    .MyCalendar .ajax__calendar_hover .ajax__calendar_day,

    .MyCalendar .ajax__calendar_hover .ajax__calendar_month,

    .MyCalendar .ajax__calendar_hover .ajax__calendar_year {

    color: black;

    }

    .MyCalendar .ajax__calendar_active .ajax__calendar_day,

    .MyCalendar .ajax__calendar_active .ajax__calendar_month,

    .MyCalendar .ajax__calendar_active .ajax__calendar_year {

    color: black;

    font-weight:bold;

    }   

在页面上显示当前页面的首选语言<%= System.Globalization.CultureInfo.CurrentCulture.NativeName %>

关于本地化技术:http://www.cnblogs.com/sufei/archive/2009/09/27/1574863.html(本地化1,2)

 

 

 

8.CascadingDropDown(级联下拉框控件)

 

http://www.cnblogs.com/abcdwxc/archive/2007/10/30/943358.html

http://www.cnblogs.com/xinjunjie/archive/2006/08/15/477769.html

http://www.cnblogs.com/dushouke/archive/2008/05/22/1205180.html

http://www.cnblogs.com/yulei/archive/2007/10/25/937269.html|荐

http://dflying.cnblogs.com/archive/2006/05/08/Atlas_Control_Toolkit_Demo__Using_CascadingDropDown_with_a_Data

base.html|荐

http://blog.csdn.net/dujingjing1230/archive/2009/06/20/4284271.aspx|荐

http://kb.cnblogs.com/a/1497672/|推荐

 

用来扩展DropDownList控件,最常见的例子就是填写地址时先选国家再选省份再选城市,微软给的例子是在XML里存储数据,而我们一般都是用数据库存储数据,所以我们来看一个用数据库存储数据的例子:

HTML:

     <asp:ScriptManager ID="ScriptManager1" runat="server">

     </asp:ScriptManager>

     <asp:DropDownList ID="DropDownList1" runat="server">

     </asp:DropDownList>

     <asp:DropDownList ID="DropDownList2" runat="server">

     </asp:DropDownList>

     <asp:DropDownList ID="DropDownList3" runat="server" AutoPostBack="True" 

      onselectedindexchanged="DropDownList3_SelectedIndexChanged">

     </asp:DropDownList>

    <ajax:CascadingDropDown ID="DropDownList1_CascadingDropDown" runat="server" Enabled="True"  TargetControlID="DropDownList1" Category="category" PromptText="请选择一个新闻类别" LoadingText="载入类别中..." ServicePath="MyCascadingWebService.asmx" ServiceMethod="GetNewCate">

    </ajax:CascadingDropDown>

    <ajax:CascadingDropDown ID="DropDownList2_CascadingDropDown" runat="server" Enabled="True"  TargetControlID="DropDownList2" Category="title" PromptText="请选择一个新闻标题" LoadingText="载入标题中..."  ServicePath="MyCascadingWebService.asmx" ServiceMethod="GetNewTitle" ParentControlID="DropDownList1">

    </ajax:CascadingDropDown>

    <ajax:CascadingDropDown ID="DropDownList3_CascadingDropDown" runat="server" Enabled="True"  TargetControlID="DropDownList3" Category="comment" PromptText="请选择一个新闻评论" LoadingText="载入评论中..." ServicePath="MyCascadingWebService.asmx" ServiceMethod="GetNewComment" ParentControlID="DropDownList2">

    </ajax:CascadingDropDown>

    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">

    <ContentTemplate>

    <asp:Label ID="Label1" runat="server" Text=""></asp:Label>

    </ContentTemplate>

        <Triggers>

            <asp:AsyncPostBackTrigger ControlID="DropDownList3" 

                EventName="SelectedIndexChanged" />

        </Triggers>

    </asp:UpdatePanel>

主要属性:

TargetControlID(目标DropDownList控件ID)

Category(属性值与WebService服务里的WebMethod方法的参数有关,一般不用,具体用法:上边的第4个链接里有讲)

PromptText(用户没有操作时给用户的提示文本)

LoadingText(与服务器交互时显示的文本)

ServicePath(WebService服务文件的路径,不要混淆ScriptPath与ServicePath这俩属性)

ServiceMethod(WebService服务文件里的方法)

在讲AutoComplete控件时我们也提到了以上两个属性,这其实是与我们之前在http://kendezhu.iteye.com/blog/752240里讲的在ScriptManager中注册web服务,在客户端JavaScript中异步调用服务器端Web Service有联系,但那是我们自定义的客户端JavaScript,而使用Ajax控件则不需要那么麻烦,微软已经帮我们做好了,只要设置这两个属性就可以了。

ParentControlID(下级DropDownList的上级DropDownList的ID)

这里与UpdatePanel有关的后置代码:

      protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)

        {

            string newcatepory = DropDownList1.SelectedItem.Text;

            string newtitle = DropDownList2.SelectedItem.Text;

            string newcomment = DropDownList3.SelectedItem.Text;

            if (string.IsNullOrEmpty(newcatepory))

            {

                Label1.Text = "请选择新闻类别";

            }

            else if (string.IsNullOrEmpty(newtitle))

            {

                Label1.Text = "请选择新闻标题";

            }

            else if(string.IsNullOrEmpty(newcomment))

            {

                Label1.Text="请选择新闻评论";

            }

            else

            {

                Label1.Text = string.Format("新闻类别{0}<br/>新闻标题{1}<br/>新闻评论{2}<br/>", newcatepory, newtitle, newcomment);

            }

        }

关于UpdatePanel及其Triggers属性的解释在http://kendezhu.iteye.com/blog/752240里的UpdatePanel的使用有解释。

不过要完成这个效果要将Page里的EnableEventValidation属性设置为false(微软给出的例子就是这么设置的)

关于EnableEventValidation属性:http://msdn.microsoft.com/zh-cn/library/system.web.ui.page.enableeventvalidation.aspx

http://www.cnblogs.com/asp600/archive/2006/11/04/550216.aspx

更多关于Page类的属性:http://msdn.microsoft.com/zh-cn/library/system.web.ui.page_properties.aspx

WebService:

 //先说明一下有些要引入的命名空间的意义

 using AjaxControlToolkit;  //CascadingDropDownNameValue类型

 using System.Collections.Specialized;  //StringDictionary字符串字典类

 [System.Web.Script.Services.ScriptService]

    public class MyCascadingWebService : System.Web.Services.WebService

    {

     //可以看出一般是有几个DropDownList就有几个相应的[WebMethod]方法,但也不一定,可以看前面提到的关于Category属性的用法

        [WebMethod]

    //CascadingDropDown要求其[WebMethod]方法返回类型是CascadingDropDownNameValue类型的数组,由其名字也可以看出该类型可以存储键值对(键,值都是字符串类型),具体可看下面的list.Add就明白了,由于下级下拉框是根据上级下拉框的值来决定显示什么内容的,所以"键"为在上级下拉框显示的数据,"值"为下级下拉框所要显示的数据的 "依据"

        public CascadingDropDownNameValue[] GetNewCate(string knownCategoryValues, string category)

        {

            List<CascadingDropDownNameValue> list = new List<CascadingDropDownNameValue>();

            SqlConnection myCon = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial 

Catalog=newsystem;Integrated Security=True");

            myCon.Open();

            SqlCommand myCmd = new SqlCommand("select name,id from catepory", myCon);

            SqlDataReader myDR = myCmd.ExecuteReader();

            while (myDR.Read())

            {                                                                                        // 键               // 值

    list.Add(new CascadingDropDownNameValue(myDR["name"].ToString(), myDR["id"].ToString()));

            }

            myCon.Close();

            myDR.Close();

            return list.ToArray();

        }

        [WebMethod]

     //与讲AutoComplete控件时一样,方法的返回值与方法内的参数都不能改动

     //一个方法的方法名+参数=方法签名,而方法重载是指方法签名中的方法名相同而参数不同

        public CascadingDropDownNameValue[] GetNewTitle(string knownCategoryValues, string category)

        {

            List<CascadingDropDownNameValue> list = new List<CascadingDropDownNameValue>();

     //值得提到的是每一个下级下拉框[WebMethod]方法里的knownCategoryValues参数都是其上级下拉框(以及上级的上级...上级下拉框直到最上级)当前选择的项对应键值对组成的字符串(不过这里的键可不是上一级下拉列表框选择的键,而是级联下拉框控件的Category属性的值,所以Category属性可以用来区分不同级联下拉框控件,同时该属性的值将被传到category参数那里),具体形式是键1(第一个级联下拉框控件的Category属性的值):值1;键2(第二个级联下拉框控件的Category属性的值):值2;键3:值3;等等。要获得本下拉框要显示的数据的"依据(就是上一级下拉框的"值")",有两种方法,一种是如下,将传来的     

 

knownCategoryValues根据:和;返回字符串数组,然后用所以取到要取的"值",但要注意,上一级下拉框的"值"是该数的最后一个元素,因此你还要数一下该字符串数组里有几个元素。

   //比如说有四级下拉框,那么最后一个下拉框得到的knownCategoryValues值就是1:1;2:2;3:3;那就要取最后那个3了。

            string[] strs = knownCategoryValues.Split(':', ';');

            SqlConnection myCon = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial 

Catalog=newsystem;Integrated Security=True");

            myCon.Open();

            string cateid = strs[1];

            SqlCommand myCmd = new SqlCommand("select title,id from news where cateid=@cateid", myCon);

            myCmd.Parameters.AddWithValue("@cateid", cateid);

            SqlDataReader myDR = myCmd.ExecuteReader();

            while (myDR.Read())

            {

                list.Add(new CascadingDropDownNameValue(myDR["title"].ToString(), myDR["id"].ToString()));

            }

            myCon.Close();

            myDR.Close();

            return list.ToArray();

        }

        [WebMethod]

        public CascadingDropDownNameValue[] GetNewComment(string knownCategoryValues, string category)

        {

            List<CascadingDropDownNameValue> list = new List<CascadingDropDownNameValue>();

         //另一种就是利用字符串字典,CascadingDropDown的ParseKnownCategoryValuesString方法,这里的键取的是你在上一个级联下拉框控件里设置的Category属性的值,你就可以判断存不存在某个键,及根据键取值(值就是上一个下拉框的值)了。 所以你如果是动态设置上一个级联下拉框控件里设置的Category属性的值的话,最好用第一种方法。

            StringDictionary sdc = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);

            //string[] strs = knownCategoryValues.Split(':', ';');

            string newsid;

            //判断存不存在某个键

            if (!sdc.ContainsKey("title")) title就是上一个级联下拉框控件里设置的Category属性的值

            {

                return null;

            }

            else

            {

               //根据键取值

                newsid = sdc["title"].ToString(); 值就是上一个下拉框的值

            }

            SqlConnection myCon = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial             

 

Catalog=newsystem;Integrated Security=True");

            myCon.Open();

            //string newsid = strs[3]; 如果用第一种方法注意取第几个元素

            SqlCommand myCmd = new SqlCommand("select content, id from comment where  newsid =@newsid",       

 

      myCon);

            myCmd.Parameters.AddWithValue("@newsid",newsid);

            SqlDataReader myDR = myCmd.ExecuteReader();

            while (myDR.Read())

            {

                list.Add(new CascadingDropDownNameValue(myDR["content"].ToString(), myDR["id"].ToString()));

            }

            myCon.Close();

            myDR.Close();

            return list.ToArray();

        }

    }

 

补:无论webservice在哪个目录,其命名空间最好与aspx的父类cs的命名空间一样,如果用Linq to sql来操作数据库的话,他们三个的命名空间最好都一样。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值