ASP.NET在文本框中显示列表框中的选定项
我正在尝试将列表框中的所有选定项显示到文本框中。目前,我正在做以下工作,但没有成功:ASP.NET在文本框中显示列表框中的选定项,asp.net,visual-studio,textbox,listbox,loops,Asp.net,Visual Studio,Textbox,Listbox,Loops,我正在尝试将列表框中的所有选定项显示到文本框中。目前,我正在做以下工作,但没有成功: For i As Integer = 0 To lb_words.ListCount If lb_words.Selected(i) = True Then tb_text.Text &= " Presto" End If Next 应该发生的是,对于列表框lb.words中的每个选定项,我希望将其附加到文本框中。假设我的列表框包含苹果、橘子和香蕉,我选择苹果和香蕉,我
For i As Integer = 0 To lb_words.ListCount
If lb_words.Selected(i) = True Then
tb_text.Text &= " Presto"
End If
Next
应该发生的是,对于列表框lb.words中的每个选定项,我希望将其附加到文本框中。假设我的列表框包含苹果、橘子和香蕉,我选择苹果和香蕉,我的文本框文本应该是苹果香蕉
我刚刚向ASP.NET做了自我介绍,所以请保持简单:D谢谢。试试这个:
Dim s as String = ""
For each x as ListItem in lb_words.Items
if x.Selected Then s &= x.Text & " "
Next
一种解决方案是重写.ToString方法以连接列表中的所有值。aspx页面:
<asp:ListBox ID="myList" runat="server" SelectionMode="Multiple">
<asp:ListItem>Apple</asp:ListItem>
<asp:ListItem>Orange</asp:ListItem>
<asp:ListItem>Grapes</asp:ListItem>
</asp:ListBox>
<br/>
<asp:TextBox id="myText" runat="server"></asp:TextBox>
代码隐藏C
StringBuilder sb=new StringBuilder();
for (int i = 0; i < myList.Items.Count; i++)
sb.Append(myList.Items[i].Selected ? myList.Items[i].Text + " " : "");
myText.Text=sb.ToString();
您可以使用lb_words.SelectedItems,而不是遍历所有记录并在其中查找所选项目。您可以使用以下代码:
Dim s As New StringBuilder()
For Each item As Object In Me.lb_words.SelectedItems
s.Append(item)
s.Append(" ")
Next
Me.TextBox1.Text = s.ToString()
如果您选择Apple&Banana,您的文本框将包含“Apple Banana”如果您使用的是数据绑定列表框,请使用按钮单击事件尝试此代码:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For Each objDataRowView As DataRowView In Me.ListBox1.SelectedItems
Me.TextBox1.Text &= (objDataRowView("ITEM LIST").ToString() & " ; ")
'here "ITEM LIST" is the "column name" which is used as DATASOURCE for LISTBOX1
Next
End Sub
问题是,他不想要所有的值,只是用户使用StringBuilder选择的值会更有效。是的,但他要求简单,并且附加到字符串比处理字符串生成器更简单这段代码看起来很有希望,但是我在'ListBoxItem'和'x.isselected'中遇到错误。。。我应该注意到我已经打开了Option Explicit和String吗?ListBoxItem错误为我提供了用ListItem或ListBox@tmhai-应选择选定的项目。和listboxitem应该是ListItem。我将错误归咎于午夜,我唯一选择的选项是.selecteditem、.selectedcvalue或.selectedindex…可能与您的问题有关-MsgBox在服务器端代码中不起作用。它不会在客户端上显示消息,也不会在服务器上显示消息:-好的,我删除了messagebox的内容。。。我更关注循环而不是结果。。。因为我的循环是问题所在,所以asp.net listbox没有SelectedItems方法。如果添加了属性SelectionMode=multiple,则使用此代码可以显示多个项目,而不是listbox web服务器控件中的一个项目
foreach (ListItem Mail in ListBox1.Items)
{
if (Mail.Selected)
{
Mail.Selected = true+",";
mail.To.Add(Mail.ToString());
}
protected void Button1_Click(object sender, EventArgs e)
{
//to display multiple items
String it =" ";
foreach (ListItem item in listbox.Items)
{
if (item.Selected)
{
it = it + ", " + item.Text;
}
Label1.Text = it;
}
}