Adding Items From Listbox to List - asp.net

A simple, rather open ended question. I am wanting to add all items in a Listbox to an object, to later print that those items into a database. Is the best practice for adding all items in a Listbox to an array?
Thanks

Since you've commented that you are using ASP.NET, you can use a loop:
Dim allListBoxItemsText = New List(Of String)
For Each item As ListItem In listBox1.Items
allListBoxItemsText.Add(item.Text)
Next
or LINQ:
Dim items = From item In listBox1.Items.Cast(Of ListItem)()
Select item.Text
allListBoxItemsText = items.ToList() ' if you want an array use ToArray

Id use the standard declare an array and loop through it. I am sure there is a more elegant solution but it works.
Dim array(listbox1.items.count-1) As String
Dim i as integer = 0
For i = 0 to listbox1.items.count -1
array(i) = listbox1.items(i)
Next

Related

Sorting a datatable

I have an asp.net listbox on my page, that I want to sort.
E.g: listbox(lstChooseFields)
MY VB code:
Private Sub LoadColumns()
If drpScreen.SelectedIndex > -1 Then
Dim daLookup As New LookupTableAdapters.LookupTableAdapter
Dim dtLookup As New System.Data.DataTable
dtLookup = daLookup.GetNestedControlValues("EM", "ExcelExport.aspx", "drpScreen", "drpScreen", drpScreen.SelectedValue)
lstChooseFields.DataSource = dtLookup
lstChooseFields.DataValueField = "LKP_ControlValue"
lstChooseFields.DataTextField = "LKP_ControlText"
lstChooseFields.DataBind()
'Dispose
daLookup.Dispose()
End If
End Sub
I have done some searching and found something like 'dtLookup.DefaultView.Sort = "LKP_ControlText" that I can use but it does not work. I don't want to sort in my database only on this page, this listbox (lstChooseFields).
So if you want to sort for the datatable then you have tried dtLookup.DefaultView.Sort = "LKP_ControlText" but you have missed out one piece of word there dtLookup.DefaultView.Sort = "LKP_ControlText asc". This generally works if LKP_ControlText is a column name in the datatable
You must use the word ascthere. which i couldnt find in your question.
After getting the dataTable sorted you can copy the same structure to another datatable if u want by using
Dim dtDuplicateLookup As New DataTable()
dtDuplicateLookup = dtLookup.DefaultView.ToTable(True)
and then access dtDuplicateLookup for further use if you want to retain the previous datatable as it is.
Use the .sorted property for the list box as shown here.
lstChooseFields.Sorted = True
UPDATE: your method was right but just tune it this way. I think you missed the DESC part. The second expression tells it how to sort the dataview.
Dim dataView As New DataView(table)
dataView.Sort = " column_name DESC" //DESC or ASC as per requirement
Dim dataTable AS DataTable = dataView.ToTable()
Else try this. After sorting a defaultview, generally you have to loopback through it
foreach(DataRowView r in table.DefaultView)
{
//... here you get the rows in sorted order
//insert the listbox items one by one here using listbox.add or listbox.insert commands
}

How to retrieve number of checked items in checklistbox in ASP.NET

I've been trying this for about 30 minutes and can't find an answer.
How do I retrieve the number of checked items in a checklistbox in ASP?
Everywhere else on the internet says to use cblList.CheckedItems but the CheckedItems property isn't showing up for me in the Intellisense? Am I forgetting to include something? It's driving me bonkers. I'm using VB.NET for this ASP assignment.
CheckedItems is a winforms property, the webforms CheckBoxList supports also multi-selection, but it does not provide a method or property to retrieve the selected items directly. But you could use this little LINQ query:
IEnumerable<ListItem> selectedItems = CheckBoxList1.Items.Cast<ListItem>()
.Where(li => li.Selected);
VB.NET:
Dim selectedItems = From item In CheckBoxList1.Items.Cast(Of ListItem)()
Where item.Selected
If you don't want to use LINQ as commented, use a loop:
Dim selected = New List(Of ListItem)
For Each item As ListItem In CheckBoxList1.Items
If item.Selected Then selected.Add(item)
Next
Dim numSelected = selected.Count

getting the values of checkboxes in a checkboxlist control

I have an asp:CheckboxList on my page and I need to get the values of the checked checkboxes.
So I have a linq query that I then loop through, but I've discovered that there is no way to retrieve the values associated with the individual checkboxes.
Here is my code:
Dim checkboxValues = cblmyCheckboxes.Controls.OfType(Of CheckBox)().Where(Function(c) c.Checked)
For Each c As CheckBox In checkboxValues
Response.Write(c.Value)
Next
How can I get the values?
Thanks
You need to use Selected instead of Checked
var selectedValues = (CheckBoxList1.Items.Cast<ListItem>()
.Where(i => i.Selected)
.Select(i => i.Value))
.ToList();
Dim selectedValues = (CheckBoxList1.Items.Cast(Of ListItem)()
.Where(Function(i) i.Selected)
.[Select](Function(i) i.Value))
.ToList()
Your Checkbox List contains ListItem and not checkbox. So cblmyCheckboxes.Items is a ListItemCollection
Really, a quicker and easier way would be:
For Each li as ListItem in cblmyCheckboxes.Items
If (li.Selected) Then
Dim XX = li.Value
'' Do something with Value
End If
Next
By using LINQ you're effectively looping through the checkbox lists items (in the background of your LINQ function (which is wrong anyway) and then also looping again in your For Each - might as well just do the one...

How do I get all the values in a listbox when looping through them?

I'm currently trying to move through all the values added to a listbox by the user, however, I want to retrieve the actual value of each item in the listbox and not the text.
I've gotten so far with the code below, but that only gets the text and not the value.
For Each item In SelectedStoresLB.Items
Dim tCompany As Integer = CInt(Left(item.ToString, 1))
Dim tStore As String = Right(item.ToString, 3)
Dim tReason As String = ReasonTxt.Text
insertSQL = "INSERT INTO [CommsDownLog] ([DimCompanyID],[PervasiveStoreNumber],[DownReason]) VALUES (" & tCompany & ", '" & tStore & "', '" & tReason & "')"
Dim insertRow = New SqlCommand(insertSQL, objConn)
Try
objConn.Open()
insertRow.ExecuteNonQuery()
objConn.Close()
Catch ex As Exception
Response.Write(ex)
End Try
Next
How would I go about getting the value for each item in the collection?
item is a ListItem object - rather than call ToString on it, you should use the Text and Value properties to get the info you need.
Using VB 2010, note to get the actual values of the items in the listbox you need to use the "Content" property of the ListBoxItem object. Eg:
For i As Integer = 0 To lstSortUs.Items.Count - 1
sAllItems &= lstSortUs.Items(i).Content & ";"
Next
sAllItems = Left(sAllItems, Len(sAllItems) - 1)
arrAllItems = sAllItems.Split(";")
System.Array.Sort(arrAllItems)
Have you tried:
item.Value
You need to be careful when iterating over a ListBox because you may end up modifying the underlying collection. By using foreach as you are, you are utilizing the underlying enumerator. I recommend you modify your iterator to the following (C# example):
foreach (ListItem li in listbox.Items.ToArray())
{
if (li.Selected)
{
Controltest2.Remove(li.Value);
}
}
By doing this, you are modify the Array's collection and not the list's collection. This assumes LINQ to object and you may need to call Cast<t> to make it work in some cases.
The reason for this is below:
The foreach statement repeats a group
of embedded statements for each
element in an array or an object
collection. The foreach statement is
used to iterate through the collection
to get the desired information, but
should not be used to change the
contents of the collection to avoid
unpredictable side effects
Source: MSDN
To get the text you want after iterating, use .Value instead of .Text. Of course, there are other ways to iterate such as going in reverse with an indexed for loop, but that's another topic :)

Dropdown controls in ASP.NET 2.0

I am using a codebehind page in ASP.NET to perform a SQL query. The query is loaded into a string, the connection is established (To Oracle), and we get it started by having the connection perform .ExecuteReader into a OleDBDataReader (We'll call it DataRead). I'll try to hammer out an example below. (Consider Drop as an ASP DropDownList control)
Dim LookFor as String = "Fuzzy Bunnies"
While DataRead.Read
If LookFor = DataRead.Item("Kinds of Bunnies") Then
'Meets special critera, do secondary function'
Drop.Items.Add(DataRead.Item("Subgroup of Bunnies"))
...
End if
...
End While
This is the only way I know of doing a dynamic add to a DropDownList. However, each item in a DropDownList has a .text property and a .value property. How can we define the .value as being different from the .text in code?
The Add function can take a ListItem, so you can do
Dim li as new ListItem(DataRead.Item("Subgroup of Bunnies"), "myValue")
Drop.Items.Add(li)
Add should have an overload that accepts a ListItem object. Using that, you can usually do something like this:
Drop.Items.Add(New ListItem("Text", "Value"))
If I understand the question, Items.Add has an overload that takes a ListItem, so you could create a new ListItem object in that line:
Drop.Items.Add(new ListItem("text", "value"))
Pardon my possibly faulty VB
Dim item as New ListItem()
item.Value = "foo"
item.Text = "bar"
Drop.Items.Add(item)
You can also use the ListItem constructor (e.g. new ListItem("text", "value"))
you'd select a second column into your datareader (such as an IDENTITY field) and then assign do your Item generation like this:
Dim item as new listitem
item.text = DataRead.Item("SubGroup Of Bunnies")
item.value = DataRead.Item("ID")
Drop.Items.Add(item)
You may also want to look into the DATABIND functionality, and filtering out "FUZZY BUNNIES" in the SQL statement itself.

Resources