ListBox控件、CheckBox控件的多选功能

来源:互联网 发布:js如何获取当前时间 编辑:程序博客网 时间:2024/05/24 05:09

我们在使用控件的时候,经常会用到ListBox控件、CheckBox控件来进行选择


1.ListBox控件

我们经常会在网页或程序中看到这样的功能:


将一个ListBox控件里的选择项添加到另一个ListBox控件里,很简单,我们将左边的命名为lb1,右边的命名为lb2,然后在中间的选择Button里写代码即可:

protected void Button1_Click(object sender, EventArgs e)        {            for (int i = 0; i < lb1.Items.Count; i++)            if(lb1 .Items [i].Selected )            {                lb2.Items.Add(lb1.Items[i]);                lb1.Items.Remove(lb1.Items[i]);                i--;            }        }


代码及其简单易懂,要注意的是,要选择ListBox控件的属性,设置SelectionMode由"Single"改为"Multiple",不然会出现选择项为多个时报错的状况。

2.CheckBoxList控件

一般应用时效果如下图:


控件命名为cbl1,直接书写Buttion的代码即可

protected void Button1_Click(object sender, EventArgs e)        {            foreach (ListItem itm in cbl1.Items)            {                if (itm.Selected)                Label1.Text += itm.Text + "";            }        }
运行结果如图:




3.RadioButtionList控件、

与2中的CheckBoxList控件用法其实差不多,除了只能选择一个,直接上代码:

protected void Button2_Click(object sender, EventArgs e)        {            foreach (ListItem itm in rbl1.Items)            {                if (itm.Selected)                Label1.Text += itm.Text + "";            }        }



0 0