Dropdown controls in ASP.NET 2.0 - asp.net

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.

Related

Verify existence of an item in a dropdownlist

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

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

Add New Item to Already Bound ListView in ASP Net (Unable to set DataKeys/FieldName)

My overall goal is to add fake/unbound items to a listview control (for final HTML Table output reasons). This is a code behind solution. Users will not be adding items as it will be outputted in a rigid table.
I have looked at several examples and while this is easy for a dropdown it is not for listview.
The code below works without error, but my item is not shown on runtime. I think the class is not setting the item fieldname correctly, but I can't figure out the right syntax to fix it.
ColumnNameAList.DataSource = PeriodDataView
ColumnNameAList.DataBind()
Dim test As New Example1("ColumnNameA")
Dim newItem As New ListViewDataItem(ColumnNameAList.Items.Count, ColumnNameAList.Items.Count)
newItem.DataItem = test
ColumnNameAList.Items.Insert(ColumnNameAList.Items.Count, newItem)
ColumnNameAList.Items.Add(newItem)
Here is the Example1 class that is supposed to set the DataValueField:
Public Class Example1
Public Sub New(ColumnNameA__1 As String)
ColumnNameA = ColumnNameA__1
End Sub
Private m_ColumnNameA As String
Public Property ColumnNameA() As String
Get
Return m_ColumnNameA
End Get
Set(value As String)
m_ColumnNameA = value
End Set
End Property
End Class
This outputs my original datasource list, but not the added item.
<ItemTemplate>
<td>
<%# Eval("ColumnNameA")%>
</td>
</ItemTemplate>
In the end I could only reliably solve this with a codebehind solution.
I made a copy of the original datasource, modified my copy and then databound to it.
Dim MyOriginalTableSource As Data.DataView = DataManager.example()
Dim ModifiedTable As DataTable = MyOriginalTableSource.ToTable
'do stuff here
Mylistbox.DataSource = ModifiedTable
Mylistbox.DataBind()
Won't work for everyone, but in this case it works fine for me.
There could be a couple of issues with the way you are approaching this, including that the ListView is already databound and that you are both adding and inserting the newItem.
When we have a scenario like this, we take one of two approaches:
1) Add the new item to the data source before the source is data bound.
2) Remove databinding and manually create each of the list view items, then add your new item at the beginning or end of the loop.
Another way to do it would be to inject it into the sql.
select col1, col2, col3 from table1 union select '1','2','3'
this would ensure that the item is always added, and asp.net doesn't need to know or care.
You can add this into the sql query or add it from the behind code before binding query. if you are not binding with sql, you can also do this to any list item with LINQ

Is it possible to do a linq query on a GridView (ASP.NET)?

Basically I have a datakey that I'd like to query from my GridView instead of looping through all the rows and comparing the key of each row. So I was wondering if it was possible to just do a linq query on the gridview (not datatable) and filter with the datakey.
Not sure how to use DataKeyNames directly, because Column doesn't have any information about data field name it's coming from. In the example below, I use SortExpression to get column index which is used for filtering.
EDIT: The most important part here is the casting, which enables you to use all the fancy extension methods designed for IEnumerable<T>.
int idColumnIndex = MyGrid.Columns.Cast<DataControlField>().Where(e => e.SortExpression == "ID").Select(e => MyGrid.Columns.IndexOf(e)).FirstOrDefault();
var row = MyGrid.Rows.Cast<GridViewRow>().Where(e => e.Cells[idColumnIndex].Text == "421").FirstOrDefault();
Everything is possible!
Gridview in itself is nothing. It's just a UI, the data is in its source be it a datatable or dataset and you can use linq to query them.
As far as I understand the theory of LINQ, it can be performed on any list. As a datasource in a gridview is in essence a list, you should be able to use LINQ on that datasource of the gridview.
Try this example:
http://weblogs.asp.net/scottgu/archive/2006/05/14/Using-LINQ-with-ASP.NET-_2800_Part-1_2900_.aspx
I did something similar to this with a repeater, and maybe it will help... or you can just disregard it if it doesn't. In my situation I databound the repeater and allowed users to modify the data before exporting it to XML. The following LINQ loops through each row in the repeater, uses findcontrol to grab the control from the datarow and then uses Linq to XML, but this could be used to generate objects using LINQ to Objects. rp is the repeater, cbIgnore is a checkbox which if the users checks it the row is not expored.
Dim doc As New XDocument( _
New XDeclaration("1.0", "ISO-8859-1", "true"), _
New XElement("Schedule_Import", _
From c As RepeaterItem In rp.Items _
Where (c.ItemType = ListItemType.Item Or c.ItemType = ListItemType.AlternatingItem) _
AndAlso DirectCast(c.FindControl("cbIgnore"), HtmlInputCheckBox).Checked = False _
Select New XElement("activity", _
New XElement("code", DirectCast(c.FindControl("txtAC"), TextBox).Text), _
New XElement("starttime", DirectCast(c.FindControl("dtfStart"), DateTimeField).SelectedDateTime), _
New XElement("endtime", DirectCast(c.FindControl("dtfEnd"), DateTimeField).SelectedDateTime), _
New XElement("description", DirectCast(c.FindControl("txtTitle"), TextBox).Text))))

Inheriting DropDownList and adding custom values using its DataSourceObject

I'm inheriting a DropDownList to add two custom ListItems. The first item is "Select one..." and the second item gets added at the end, it's value is "Custom".
I override DataBind and use the following code:
Dim data As List(Of ListItem) = CType(DataSource, List(Of ListItem))
data.Insert(0, New ListItem("Select one...", SelectOneListItemValue))
If DisplayCustomOption Then
data.Insert(data.Count, New ListItem("Custom", CustomListItemValue))
End If
DataSource = data
MyBase.DataBind()
The problem is this code won't work if the DataSource is anything other than a List of ListItem. Is there a better way of doing this?
You could make the assumption that the data source always inherits IList, in which case you could do the following:
Dim data As IList = CType(DataSource, IList)
data.Insert(0, New ListItem("Select one...", SelectOneListItemValue))
' And so on...
Of course, this assumes that whatever the data source is, it allows you to add objects of the type ListItem. But this might be generic enough for what you need.
You could just leave the databind alone and add your special Items in the DataBound event handler.
Protected Sub MyDropDownList_DataBound(sender As Object, e As EventArgs) _
Handles MyDropDownList.DataBound
MyBase.Items.Insert(0, New ListItem("Select One...", SelectOneListItemValue))
If DisplayCustomOption Then
MyBase.Add(New ListItem("Custom", Custom))
End If
End Sub
(My VB.NET is limited, so you may need to adjust syntax)

Resources