I' trying to use a Linq query to find and set the selected value in a drop down list control.
Dim qry = From i In ddlOutcome.Items _
Where i.Text.Contains(value)
Dim selectedItem As ListItem = qry.First
ddlOutcome.SelectedValue = selectedItem.Value
Even though the documentation says that the DropDownList.Items collection implements IEnumerable I get an error in the Where clause that Option Strict ON disallows late binding!
I can give you an answer in C#, and i hope it helps you.
The easiest way it to use the methods of DropDownlist, better than linq query:
DropDownList1.SelectedIndex =
DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText("2"));
If you want the linq query it would be like this:
var selected=from i in DropDownList1.Items.Cast<ListItem>()
where ((ListItem)i).Text.Contains("2") select i;
DropDownList1.SelectedValue = selected.ToList()[0].Text;
Anyone thought about:
foreach (ListItem li in drp.Items.Cast<ListItem>().Where(li => li.Value == ""))
{
li.Selected = true;
}
Thank you for the suggestions, they were both helpful in leading me to a workable solution. While I agree that using the methods of the drop list itself should be the way to go, I don't have an exact match on the text of the items in the list so I needed another way.
Dim qry = From i In ddlOutcome.Items.Cast(Of ListItem)() _
Where i.Text.Contains(value)
qry.First().Selected = True
The linq query seems preferable to iterating through the list myself, and I learned something in the process.
My vb.net is shaky, (c# guy) but try:
Dim qry = From DirectCast(i, ListItem) In ddlOutcome.Items ...
I may have the DirectCast syntax wrong, but you know where I'm coming from. The problem is that at compile time, Items is not verifiable as as a collection of ListItem because IEnumerable's Current property returns Object. Items is not a generic collection.
-Oisin
simple way to select using following code
foreach (ListItem i in DropDownList1.Items)
{
DropDownList1.SelectedValue = i.Value;
if (DropDownList1.SelectedItem.Text=="text of your DropDownList")
{
break;
}
}
Related
How do I check for the existence of an item in a dropdownlist in vb.net?
Here's my not working code:
dim ddlTestDropdown as dropdownlist
ddlTestDropdown = New DropDownList()
If(ddlTestDropdown.Items.FindByValue("42") Is Not nothing)
Console.WriteLine("It's there")
End If
it won't let me compare the returned ListItem to nothing
Update: The error is from saying Is Not the fix is to say:
If(Not ddlTestDropdown.Items.FindByValue("42") Is Nothing)
Alternate answer:
Here's what I found to do this. Like #praythyus tried you need to test for contains, but vb.net only lets you do contains on a listitem. So I combined what I did with what he did and this worked:
Dim SetThisIfExists = ddlTestDropdown.Items.FindByValue("42")
If(ddlTestDropdown.Items.Contains(SetThisIfExists))
ddlTestDropdown.SelectedIndex = ddlTestDropdown.Items.IndexOf(SetThisIfExists)
End If
Sorry for giving C# syntax. Can you try with
as #RS said, you need to fill the ddl after initializing.
if(ddlTestDropdown.Items.Contains("42"))
{
}
Or instead of FindByValue can you use FindByText
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
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...
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 :)
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.