ListBox基本功能使用方法

2011-06-09 13:23:16|  分类: .NET/C# |  标签:listbox基本功能使用方法   |举报 |字号大中小 订阅

 
 
  1. ListBox基本功能使用方法

ListBox基本功能首先是列表项的添加,客户端实现代码添加在listbox实例化代码中间,例如:

<asp:ListItem Value="value" Selected=True>Text</asp:ListItem>

若在服务器端实现,为避免每次加载时执行添加列表项,上述代码包含在下面代码中:

if(!IsPostBack)

{

}

WebForm页面上须添加2个listbox(listbox1和lixtbox2)和2个命令按钮,listbox1不为空。列表项从listbox1添加到listbox2须在Button1单击事件中调用Add方法:

ListBox2.Items.Add(ListBox1.SelectedValue);

若要从listbox2中删除列表项的话须在Button2单击事件中调用Remove方法:

ListBox2.Items.Remove(ListBox2.SelectedValue);

列表项从listbox1添加到listbox2后,列表项从listbox1中删除:

int i=0;

while(i<ListBox1.Items.Count)

{

if(ListBox1.Items[i].Selected==true)

{

ListBox2.Items.Add(ListBox1.Items[i]);

ListBox1.Items.Remove(ListBox1.Items[i]);

}

else

i+=1;

}

这样只能实现单项添加,想要实现多项添加,首先设置ListBox1的SelectionMode属性值Multiple,ListBox1允许多项选中。

在Button1单击事件中添加

foreach(ListItem MyItem in ListBox1.Items)

if(MyItem.Selected==true)

ListBox2.Items.Add(MyItem);

想要一次清空ListBox2中所有选项可在Button2单击事件中调用clear方法,

ListBox2.Items.Clear();

若列表项已经添加,不允许二次添加,Button1单击事件中的代码包含在:

if(ListBox2.Items.FindByValue(ListBox1.SelectedValue)==null)

{

}

ListBox与数据库绑定就是指定他的DataSource和DataTextField属性,

ListBox2.DataSource=数据源;

ListBox2.DataTextField="字段名";

ListBox2.DataBind();


<script type="text/javascript">
        function SelectAll()
        {
            var lst1=window.document.getElementById("<%=lb_Sourse.ClientID %>");
            var length = lst1.options.length;
             var string = window.document.getElementById("<%=hf_NewName.ClientID %>")
            for(var i=0;i<length;i++)
            {
                var v = lst1.options[i].value;
                var t = lst1.options[i].text;             
                var lst2=window.document.getElementById("<%=lb_NewName.ClientID %>");
                lst2.options[i] = new Option(t,v,true,true);
                string.value+=v;
            }
        }
        
        function DelAll()
        {
            var lst2=window.document.getElementById("<%=lb_NewName.ClientID %>");
            var length = lst2.options.length;
            for(var i=length;i>0;i--)
            {
                lst2.options[i-1].parentNode.removeChild(lst2.options[i-1]);
            }
        }
        
        function SelectOne()
        {
          var string = window.document.getElementById("<%=hf_NewName.ClientID %>")
            var lst1=window.document.getElementById("<%=lb_Sourse.ClientID %>");
            var lst2=window.document.getElementById("<%=lb_NewName.ClientID %>");
            var lstindex=lst1.selectedIndex;
            var length = lst2.options.length;
            var isExists = false;
            if(lstindex<0)
                return;
            else if(length != null)
            {
                for(var i=0;i < length; i++)
                {
                     if(lst2.options[i].text == lst1[lstindex].text&&lst2.options[i].value == lst1[lstindex].value)
                     {
                        isExists = true;
                     }
                }
            }
            else
            {
                return;
            }
            if (isExists == false)
            {
                var v = lst1.options[lstindex].value;
                var t = lst1.options[lstindex].text;
                lst2.options[lst2.options.length] = new Option(t,v,true,true);
                string.value+=v;
            }
            else
            {
                alert("所选条目已经存在");
                return false;
            }
        }
        
        function DelOne()
        {
            var lst2=window.document.getElementById("<%=lb_NewName.ClientID %>");
            var lstindex=lst2.selectedIndex;
            if(lstindex>=0)
            {
                var v = lst2.options[lstindex].value+";";
                lst2.options[lstindex].parentNode.removeChild(lst2.options[lstindex]);
            }
        }
</script>

需要解释的是由于JS脚本是在客户端执行的,因此服务器端控件是无法调用JS的,由于ID无法被找到,但用<%=lb_NewName.ClientID %>的方法就巧妙的解决得该问题,是asp控件拥有客户端id,这样就可以调用了。

希望对大家有所帮助!


ASP.NET中添加控件ListBox , 属性设为 Multiple , 则可进行多选.
就以两个listbox之间多选添加项目为例.
两个控件为listboxleft , listboxright 定义了一个动态数组用于中间存储 arrRight .具体代码如下:

//读取右边选中项目
   ArrayList arrRight = new ArrayList();
   foreach(ListItem item in this.ListBoxRight.Items) //按类型listitem读取listbox中选定项
   {
    if(item.Selected) //判断是否选中
    {
     arrRight.Add(item);
    }
   }

//右边移除选定项目 左边添加
   foreach(ListItem item in arrRight)
   {
    this.ListBoxLeft.Items.Add(item);
    this.ListBoxRight.Items.Remove(item);
   }
不能将item的添加删除直接写在if(item.Selected){}内,因为项目remove后会出现错误


添加两个listbox (ListBoxAll , ListBoxUser)    两个按钮( ButtonListDel >> , ButtonListAdd <<)

按钮的代码为:

private void ButtonListDel_Click(object sender, System.EventArgs e)
  {
   //listbox >> 删除listboxuser选中项目 将其添加入listboxall
   if(this.ListBoxUser.SelectedIndex != -1)
   {
    this.ListBoxAll.Items.Add(this.ListBoxUser.SelectedItem.Value);
    this.ListBoxUser.Items.Remove(this.ListBoxUser.SelectedItem.Value); 
   }
  }

private void ButtonListAdd_Click(object sender, System.EventArgs e)
  {
   //listbox << 
   if(this.ListBoxAll.SelectedIndex != -1)
   {
    this.ListBoxUser.Items.Add(this.ListBoxAll.SelectedItem.Value);
    this.ListBoxAll.Items.Remove(this.ListBoxAll.SelectedItem.Value);
   }
  }

1 为了确保添加不会重复 填充listbox时使两边无重复项目.

完成listbox里项目的添加、删除的关键代码:

1.通过AddRange方法添加项目:this.lbyx.Items.AddRange(new object[] {"北京","上海","天津","成都","广州","深圳","武汉"});

2.添加items:this.lbbx.Items.Add(this.lbyx.Text);

3.清空列表内的所有items:this.lbbx.Items.Clear();

4.当前所选项的编号获取:this.lbbx.SelectedIndex

5.删除某项:this.lbbx.Items.RemoveAt(this.lbbx.SelectedIndex);


在从一个ListBox选择内容copy到另外一个ListBox时候用下面的方法:

if (ListBox2.Items.IndexOf(ListBox1.SelectedItem) == -1)
        {
            ListBox2.Items.Add(new ListItem(ListBox1.SelectedValue));
            //ListBox2.Items.Add(ListBox1.SelectedItem);  <--用这个会记录状态,ListBox2不支持Multiple就出错了
}

===================================================================

<asp:listbox width="100px" runat=server>
                    <asp:listitem>Roman</asp:listitem>
                    <asp:listitem>Arial Black</asp:listitem>
                    <asp:listitem>Garamond</asp:listitem>
                    <asp:listitem>Somona</asp:listitem>
                    <asp:listitem>Symbol</asp:listitem>
                 </asp:listbox>

void RemoveAllBtn_Click(Object Src, EventArgs E) {

while (InstalledFonts.Items.Count != 0) {

AvailableFonts.Items.Add(new ListItem(InstalledFonts.Items[0].Value));
               InstalledFonts.Items.Remove(InstalledFonts.Items[0].Value);
            }
        }
当数据源改为

<asp:listbox width="100px" runat=server>
                    <asp:listitem value="1">Roman</asp:listitem>
                    <asp:listitem value="bbb">Arial Black</asp:listitem>
                    <asp:listitem value="333">Garamond</asp:listitem>
                    <asp:listitem value="4">Somona</asp:listitem>
                    <asp:listitem value="5">Symbol</asp:listitem>
                 </asp:listbox>

listbox.items.count会一直为总数,不会顺while循环的变化,可以修改为如果方法:

#region button

private void btnRemoveAll_Click(object sender, System.EventArgs e)
  {
   while (lstSelDpt.Items.Count != 0) 
   {
    lstAllDpt.Items.Add(lstSelDpt.Items[lstSelDpt.Items.Count-1]);
    lstSelDpt.Items.RemoveAt(lstSelDpt.Items.Count-1);
   }

}

private void btnRemove_Click(object sender, System.EventArgs e)
  {
   while(lstSelDpt.SelectedIndex != -1) 
   {
    lstAllDpt.Items.Add(lstSelDpt.Items[lstSelDpt.SelectedIndex]);
    lstSelDpt.Items.Remove(lstSelDpt.Items[lstSelDpt.SelectedIndex]);
   }
  }

private void btnAdd_Click(object sender, System.EventArgs e)
  {   
   while (lstAllDpt.SelectedIndex != -1) 
   {
    lstSelDpt.Items.Add(lstAllDpt.Items[lstAllDpt.SelectedIndex]);
    lstAllDpt.Items.Remove(lstAllDpt.Items[lstAllDpt.SelectedIndex]);
   }
  }

private void btnAddAll_Click(object sender, System.EventArgs e)
  {
   while (lstAllDpt.Items.Count != 0) 
   {
    lstSelDpt.Items.Add(lstAllDpt.Items[lstAllDpt.Items.Count-1]);
    lstAllDpt.Items.Remove(lstAllDpt.Items[lstAllDpt.Items.Count-1]);
   }

}

#endregion


用dotnet做一个项目的过程中,遇到了一个ListBox的问题:通过在一个ListBox中双击,把选中的项添加到另一个ListBox中,但ListBox控件本身并没有该事件,那么如何实现呢?我就想到了客户端脚本javascrit,通过查阅相关资料,终于把这个问题解决了,现在写出来与大家分享,希望能对大家有所帮助。
        这里有三个问题:
        第一:双击所要执行的javascript代码是什么?
                    注意:javascript代码的语法要正确,即每一行都要以“;”结尾;
                    function change()
                        {
                             var addOption=document.createElement("option");
                             var index1;
                             if(document.Form1.ListBox1.length==0)return(false);
                              index1=document.Form1.ListBox1.selectedIndex; 
                             if(index1<0)return(false);
                              addOption.text=document.Form1.ListBox1.options(index1).text;
                              addOption.value=document.Form1.ListBox1.value;
                             document.Form1.ListBox2.add(addOption);
                             document.Form1.ListBox1.remove (index1);
                         }
        第二:如何将 javascript 代码转换为C#代码?
                    public static void ListBox_DblClick(Page page,System.Web.UI.WebControls.WebControl webcontrol,string                                 SourceControlName,string TargetControlName)
                     {
                           SourceControlName = "document.Form1." +  SourceControlName;
                           TargetControlName = "document.Form1." +  TargetControlName;
                           string js = "<script language=javascript> function change(SourceControlName,TargetControlName)";
                           js += "{";
                           js +=     "var addOption=document.createElement('option'); \n";
                           js += "  var index1; \n";
                           js += "if(SourceControlName.length==0)return(false);\n";
                           js += "  index1=SourceControlName.selectedIndex; \n ";
                           js += "  if(index1<0)return(false);\n";
                           js += " addOption.text=SourceControlName.options(index1).text; \n";
                           js += "addOption.value=SourceControlName.value; \n";
                           js += "TargetControlName.add(addOption); \n";
                           js += "SourceControlName.remove (index1) \n";

js +="}";
                           js += "</script>";
                            //注册该 javascript ;
                           page.RegisterStartupScript("",js);
                            //为控件添加双击事件;
                           webcontrol.Attributes.Add("onDblClick","change(" + SourceControlName + "," + TargetControlName +                                 ");");
                      }
                    在该方法中,SourceControlName是要绑定双击事件的控件,TargetControlName是接收双击事件选定项的控件。    
                    这里有一个问题,如何让对象作为参数传给javascript的change函数,我这里采用的是用  SourceControlName  ,TargetControlName 来传递两个ListBox的Name, 然后与“document.Form1.“组合成一个串来传递给javascript的change函数,即 
                            SourceControlName = "document.Form1." +  SourceControlName;
                           TargetControlName = "document.Form1." +  TargetControlName;

第三:如何为控件添加双击事件?
                    用ControlName.Attributes.Add(“属性名称”,“函数名称或代码”);

ASP.NET listBbox控件用法的更多相关文章

  1. asp.net Listbox控件用法

    2008-02-18 19:56 来源: 作者: ListBox(列表框)控件可以显示一组项目的列表,用户可以根据需要从中选择一个或多个选项.列表框可以为用户提供所有选项的列表.虽然也可设置列表框为多 ...

  2. asp.net中Repeater控件用法笔记

    大家可能都对datagrid比较熟悉,但是如果在数据量大的时候,我们就得考虑使用 repeater作为我们的数据绑定控件了.Repeater控件与DataGrid (以及DataList)控件的主要区 ...

  3. CustomValidator控件用法

    虽然大部分时间一直从事asp.net的开发,对于一些常用的asp.net服务器端验证控件及它们的组合使用比较熟悉,如:CompareValidator ——比较验证控件RangeValidator — ...

  4. ASP.NET ValidationSummary 控件

    ASP.NET ValidationSummary 控件 Validation 服务器控件 定义和用法 ValidationSummary 控件用于在网页.消息框或在这两者中内联显示所有验证错误的摘要 ...

  5. Jquery + css 日期控件用法实例.zip

    /*==============================================================================** Filename:common.j ...

  6. asp.net分页控件

    一.说明 AspNetPager.dll这个分页控件主要用于asp.net webform网站,现将整理代码如下 二.代码 1.首先在测试页面Default.aspx页面添加引用 <%@ Reg ...

  7. asp.net ajax控件tab扩展,极品啊,秒杀其它插件

    说明:asp.net ajax控件tab要设置width和height,而且在线文本编辑器放能够放入tab中,也必须是asp.net的控件型在线文本,例如fckeditor,下面是我设置好的配置. & ...

  8. javascript获取asp.net服务器端控件的值

    代码如下: <%@ Page Language="C#" CodeFile="A.aspx.cs" Inherits="OrderManage_ ...

  9. ASP.NET控件<ASP:Button /> html控件<input type="button">区别联系

    ASP.NET控件<ASP:Button />-------html控件<input type="button">杨中科是这么说的:asp和input是一样 ...

随机推荐

  1. Android 数字签名学习笔记

    Android 数字签名学习笔记 在Android系统中,所有安装到系统的应用程序都必有一个数字证书,此数字证书用于标识应用程序的作者和在应用程序之间建立信任关系,如果一个permission的pro ...

  2. 宣布正式发布 Windows Azure 移动服务、网站及持续的服务创新

    我们努力创新,向开发人员提供多样化平台以构建最好的云应用程序并在第一时间提供给世界各地的客户.许多新应用程序都属于"现代化应用程序",即始终基于 Web,且可以通过各种移动设备进行 ...

  3. 泛型、注解、log4j

    泛型.注解.log4j 泛型:将运行阶段的类型错误提前到编译阶段. 声明泛型必须两端的一致,要么左面有,要么右边有,两边都有的两边必须一致. 泛型方法: static 之后 返回类型之前进行声明 泛型 ...

  4. iOS第三方库-CocoaLumberjack-DDLog (转)

    原文:http://blog.sina.com.cn/s/blog_7b9d64af0101kkiy.html 发现一个,很厉害的小工具,让xCode控制台输出文本有颜色! 闲话不说,上代码. 大概需 ...

  5. ios 开发 常见问题解决 (持续更新)

    1.使用cocoaPods引用第三方类库,报错:file not found   . 解决方案:设置 Project->Info->Configurations之后  clear ,然后再 ...

  6. IOS-时间与字符串互相转换

    有时会遇到这种问题,须要把时间和时间戳互相转换 比方把"这种格式 或者是把""转换成"2014-07-16 15:54:36" 首先来第一个: 当前时 ...

  7. PHP语言基础06 MySql By ACReaper

    上篇介绍了如用PHP连接上MySql进行,并进行sql语句的执行.但是我们没有介绍,如何输出处理的结果,如何获得处理的结果. 这里要先说明Mysql有两种查询处理模式,一种是有缓冲的查询处理模式,一种 ...

  8. OC语法2——OC的类,方法,成员变量的创建

    类的创建: 与Java不同的是,OC创建一个类需要两个文件(.h和.m文件) 1> xxx.h:声明文件.用于声明成员变量和方法.关键字@interface和@end成对使用. 声明文件只是声明 ...

  9. attempting to bokeyaunrun eclipse useing the jre instead of jdk,to run eclipse using

    关于eclipse运行出现,attempting to bokeyaunrun eclipse useing the jre instead of jdk,to run eclipse using错误 ...

  10. laravel post请求失败

    今天继续研究laravel,在路由里注册了一个控制器路由Route::controller(). 先get请求一个页面 class UserController extends Controller{ ...