Taking A Selected Item In A Listbox and Populate Into A Textbox
-
04-06-2021 - |
Question
Alright, I currently have a listbox being populated with a variety of files.
What I'd like to do is select a file, click the add button and populate the item name into that textbox.
Then, select another item, click the add button and populate that items named into an empty textbox.
I can get the first textbox to populate, but once I select the second item, I can't get empty textbox to display.
Here's my current code on how I'm populating the first textbox. The commented out section was for adding those items into another listbox, which worked but I need to specify a custom order, which I was I thought adding each item to a textbox.
Private Sub ButtonAdd_Click(sender As System.Object, e As System.EventArgs) Handles ButtonAdd.Click
'Dim selectedItems = (From i In ListBox1.SelectedItems).ToArray()
'For Each selectedItem In selectedItems
'ListBox3.Items.Add(selectedItem)
'ListBox1.Items.Remove(selectedItem)
'Next
TextBox1.Text = ListBox1.SelectedItem
End Sub
Any suggestions?
La solution
Try something like this:
Private Sub ButtonAdd_Click(sender As System.Object, e As System.EventArgs) Handles ButtonAdd.Click
If string.IsNullOrEmpty(TextBox1.Text) Then
TextBox1.Text = ListBox1.SelectedItem
ElseIf string.IsNullOrEmpty(TextBox2.Text) Then
TextBox2.Text = ListBox1.SelectedItem
ElseIf string.IsNullOrEmpty(TextBox3.Text) Then
TextBox3.Text = ListBox1.SelectedItem
End If
End Sub
Autres conseils
I put a quick little demo together.
First the aspx page:
<asp:ListBox id="lstItems" runat="server">
<asp:ListItem>-- Select --</asp:ListItem>
<asp:ListItem>Item 1</asp:ListItem>
<asp:ListItem>Item 2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
<asp:ListItem>Item 4</asp:ListItem>
</asp:ListBox>
<asp:Panel ID="pnlTextboxes" runat="server">
<asp:TextBox ID="txt1" runat="server" />
<asp:TextBox ID="txt2" runat="server" />
<asp:TextBox ID="txt3" runat="server" />
<asp:TextBox ID="txt4" runat="server" />
</asp:Panel>
<asp:Button id="btnAdd" Text="Add" runat="server" />
And the code behind:
Protected Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
If lstItems.SelectedIndex <= 0 Then
Return
End If
For Each ctrl As Control In pnlTextboxes.Controls
If TypeOf ctrl Is TextBox Then
Dim txt = CType(ctrl, TextBox)
If String.IsNullOrEmpty(txt.Text) Then
txt.Text = lstItems.SelectedValue
Exit For
End If
End If
Next
End Sub
Note, that this doesn't track if you've already selected the item.