列表框上的多项选择 [英] multiple selection on listbox
本文介绍了列表框上的多项选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的示例代码:
My sample code:
string str = "";
foreach(ListItem lstIetm In MyListBox.Items)// through an exception here "unable to cast object of type 'System.String' to 'System.Web.UI.WebControls.ListItem'"
{
If(lstIetm.Selected)
{
str+=lstItem.Value.ToString()+",";
}
}
if(str!="")
{
str.Remove(str.LastIndexOf(','));
}
Select * from <tablename> where Id in (str)
请建议我如何解决此异常及其发生的原因.我遍历所有资源.但是我有相同的foreach循环.
[edit]添加了代码块[/edit]
please suggest me how to resolve this exception and why it occurs. i go through all the resources. but i got the same foreach loop.
[edit]code block added[/edit]
推荐答案
if (ListBox1.Items.Count > 0)
{
for (int i = 0; i < ListBox1.Items.Count; i++)
{
if (ListBox1.Items[i].Selected)
{
string selectedItem = ListBox1.Items[i].Text;
//insert command
}
}
}
你要这个吗?
或
Do you want this?
or
public string GetListBoxSelStringInComma(ListBox Listbox1)
{
string selectedItem = "";
if (Listbox1.Items.Count > 0)
{
for (int i = 0; i < Listbox1.Items.Count; i++)
{
if (Listbox1.Items[i].Selected)
{
if (selectedItem == "")
selectedItem = Listbox1.Items[i].Text;
else
selectedItem += "," + Listbox1.Items[i].Text;
}
}
}
return selectedItem;
}
和所有记录
and for all records
protected void btnSelectAll_Click(object sender, EventArgs e)
{
int _count = lstEmployees.Items.Count;
if (_count != 0)
{
for (int i = 0; i < _count; i++)
{
ListItem item = new ListItem();
item.Text = lstEmployees.Items[i].Text;
item.Value = lstEmployees.Items[i].Value;
lstSelectedEmployees.Items.Add(item);
}
}
lstEmployees.Items.Clear();
}
嗨
我认为您尝试使用"Selected"属性选择的上述代码适用于Web应用程序,而您尝试使用Windows应用程序.
您可以尝试以下代码:
Hi
I think the above code you tried with "Selected" property is for web application and you are trying with windows application.
Can you try the below code:
using System.Collections.Generic;
int itemCount = listBox1.SelectedItems.Count;
List<string> lstItems = new List<string>();
for (int i = 0; i < itemCount; i++)
{
lstItems.Add(listBox1.SelectedItems[i].ToString());
}
//string myInQuery = string.Join(",",lstItems);
string myInQuery = string.Empty;
for (int i = 0; i < lstItems.Count; i++)
{
if (myInQuery != string.Empty)
{
myInQuery = string.Format("{0},{1}",myInQuery, lstItems[i]);
}
else
myInQuery = lstItems[i];
}
这篇关于列表框上的多项选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文