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...
Related
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
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've worked out how to create a DropDownList using the following code:
<select id="salesPersonDropList" runat="server"></select>
In my .aspx page, then my code behind loops through database output running:
Dim newListItem As ListItem
newListItem = New ListItem("Title", "Value")
salesPersonDropList.Items.Add(newListItem )
What I can't figure out is how to programatically set which of the List Items created is the one to be pre-selected in the rendered DropDownList, ie, how to create what I'd write in HTML as:
<select>
<option value="1">1</option>
<option selected value="2">2</option>
</select>
Based on database output. As the code behind loops through the database output it should compare the output to a session variable and if they values match, the ListItem should be the item selected in the rendered DropDown.
Set your Selected property of the ListItem to true:
Dim newListItem As ListItem
newListItem = New ListItem("Title", "Value")
newListItem.Selected = True
salesPersonDropList.Items.Add(newListItem )
Store your results in an object that implements IEnumerable.
Loop through your resultset and then Loop through your DropDownList's Items collection. If the current Item is equal to the value in your result set set the Selected property to true
Say you have a populated datatable returned from your query.
Foreach(Datarow row in Datatable.Rows)
{
foreach (ListItem item in DropDownList.Items)
{
if (item.Value == row["columnName"])
{
item.Selected = true;
}
}
}
Please note that if your DropDownList's DataValueMember property is not set you will need ot use the Text property for comparison.
Need to test the new list items as they are being created to see if they match the session value, then just set that one to selected and add it to the list.
Dim newListItem As ListItem
newListItem = New ListItem("Title", "Value")
if(newListItem.value == SessionValue)
newListItem.Selected = True;
salesPersonDropList.Items.Add(newListItem )
This can be done in one statement in vb.net. Assume your dropdown list has the id of ddlYear, could do this:
ddlYear.Items.Insert(0, New ListItem("--- All Years ---", "All"))
This inserts the new list item at position 0, or the top of the list.
Generically:
dropdownlist.items.insert(Position, New ListItem(Text, Value)
I'm using a CheckBoxList to define which columns are displayed in a GridView. I populate the CheckBoxList using a query like
select column_name, data_type from information_schema.columns
where table_name = 'myTable'
After the user has chosen the columns (with various Data Types in them) they wish to display, they press a button and the following snippet of VB code generates the GridView.
For Each item As ListItem In chooseColsList.Items
If item.Selected Then
Dim bf As New BoundField()
'PRODUCES BUGGY RESULTS BECAUSE APPLIED TO ALL BoundFields
bf.DataFormatString = "{0:dd-MMM-yyyy}"
bf.ApplyFormatInEditMode = True
bf.DataField = item.Value
bf.HeaderText = item.Value
bf.SortExpression = item.Value
statusReportGrid.Columns.Add(bf)
End If
Next
What I want to do is to apply the DataFormatString ONLY to the columns with a 'date' Data Type in them. However, I have found no way of programmatically determining the Type of the data in the column being bound, no any way of passing this info to the Control. This information exists in the information_schema, as shown in my query, but I don't know how to extract that out and use it to dynamically setup my BoundFields. It is important to note that I'm using an SqlDataSource.
I've experimented with just about every possible solution I can think of and end up here.
Thanks in advance for your help, it is VERY appreciated :)
If you set your check box list like this:
<asp:checkboxlist id="list" runat="server"
DataTextField="column_name" DataValueField="data_type" DataSourceID="YourDSID" />
You should be able to iterate through the items and check the value of the current Item like so:
For Each item As ListItem In chooseColsList.Items
If item.Selected Then
Dim bf As New BoundField()
If StrComp(item.Value,"date") = 0 Then 'Or however datetime is returned
bf.DataFormatString = "{0:dd-MMM-yyyy}"
bf.ApplyFormatInEditMode = True
End If
bf.DataField = item.Text
bf.HeaderText = item.Text
bf.SortExpression = item.Text
statusReportGrid.Columns.Add(bf)
End If
Next
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;
}
}