Verify existence of an item in a dropdownlist - asp.net

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

Related

Simple bind value to textbox in code behind using Telerik OpenAccess

I cannot find a complete example. Found tons on grid and combobox, but not textbox. This test is to lookup a “PhoneTypeName” from a UserPhoneType table with TypeCode = “0” and assign that first value to a asp.net textbox.
Currently, I am getting “Object reference not set to an instance of an object” when setting the text box to "phonetype.FirstOrDefault.PhoneTypeName.ToString"
Using dbContext As New EntitiesModel()
Dim phonetype As IEnumerable(Of User_PhoneType) = dbContext.User_PhoneTypes.Where(Function(c) c.PhoneTypeCode = "O")
mytextbox.Text = phonetype.FirstOrDefault.PhoneTypeName.ToString
End Using
----EDIT----
I changed as suggested. I ALSO successfully bound the entire list of PhoneTypes to a droplist control...to confirm the data is accessible. It must be the way I am going about querying the table for a single record here.
I get the same error, but at "Dim type = phonetype.First..."
The record is in the table, but it does not appear to be extracted with my code.
Dim phonetype As IEnumerable(Of User_PhoneType) = dbContext1.User_PhoneTypes.Where(Function(c) c.PhoneTypeCode = "M")
Dim type = phonetype.FirstOrDefault
If Object.ReferenceEquals(type, Nothing) = False And Object.ReferenceEquals(type.PhoneTypeName, Nothing) = False Then
mytextbox.Text = type.PhoneTypeName.ToString
End If
In general there are the following two possible reasons for getting this exception:
1) The phonetype list is empty and the FirstOrDefault method is returning a Nothing value.
2) The PhoneTypeName property of the first element of the phonetype list has a Nothing value.
In order to make sure that you will not get the Object reference not set to an instance of an object exception I suggest you add a check for Nothing before setting the TextBox value. It could be similar to the one below:
Dim type = phonetype.FirstOrDefault
If Object.ReferenceEquals(type, Nothing) = False And Object.ReferenceEquals(type.PhoneTypeName, Nothing) = False Then
mytextbox.Text = type.PhoneTypeName.ToString
End If
Fixed it.
I was able to view the SQL string being generated by using this:
mytextbox.text = phonetype.tostring
I saw that the SQL contained "NULL= 'O'"
I did it like the example?!? However, when I added .ToString to the field being queried, it worked.
So the final looks like this:
Using dbContext As New EntitiesModel()
Dim phonetype As IEnumerable(Of User_PhoneType) = dbContext.User_PhoneTypes.Where(Function(c) c.PhoneTypeCode.**ToString** = "O")
mytextbox.Text = phonetype.FirstOrDefault.PhoneTypeName.ToString
End Using
BTW, Dimitar point to check for null first is good advice (+1). The value was nothing as he said.

dynamically set control ID

i have few texboxt and dropdownlist, which their id would be something like "txtName1, txtName2, txtName3..." and "ddlAction1, ddlAction2, ddlAction3...."! I would to to dynamically set the textboxt and dropdownlist id into something like this:
for i as integer = 0 to 6
a = txtName+i.text
b = ddlAction+i.SelectedValue
next i
Need help from you guys to do this! thanks....
The key is FindControl, which looks up a control by its expected ID:
For i As Integer = 0 To 5
Dim txt As TextBox = TryCast(Me.Page.FindControl("txtName" & i.ToString()), TextBox)
Dim ddl As DropDownList = TryCast(Me.Page.FindControl("ddlAction" & i.ToString()), DropDownList)
If txt IsNot Nothing AndAlso ddl IsNot Nothing Then
Dim a As String = txt.Text
Dim b As String = ddl.SelectedValue
End If
Next
It will return null/nothing if a control with that ID isn't found.
Note that FindControl will only search the given control's (or Page's) immediate children, not the entire control tree. To search recursively, you need to use your own FindControl method.
Private Function FindControlRecursive(ByVal control As Control, ByVal id As String) As Control
Dim returnControl As Control = control.FindControl(id)
If returnControl Is Nothing Then
For Each child As Control In control.Controls
returnControl = child.FindControlRecursive(id)
If returnControl IsNot Nothing AndAlso returnControl.ID = id Then
Return returnControl
End If
Next
End If
Return returnControl
End Function
.Net requires you to resolve your variable names at compile time, rather than runtime like your code is trying to do. This is a good thing, as it prevents you from making certain kinds of errors. But it does mean you'll need to look at an alternative approach for this particular problem.
One option is a FindControl -based method. But odds are the controls you care about are grouped together on the page. If they aren't already, put them in a common container control, like a panel. Then you can do something like this (requires System.Linq):
For Each t As TextBox In MyContainer.Controls.OfType(Of TextBox)()
a = t.Text
Next t
For Each d As DropDownList In MyContainer.Controls.OfType(Of DropDownList)()
b = d.SelectedValue
Next d
Also, I hope you're really doing something other than assignment inside your loop. Otherwise, most of the work is for nothing as you will exit the loop having simply assigned the value from the last iteration to your variable.
Finally, it seems like these controls might work in pairs. To me, that's a situation that calls out for you to implement a user control.
I'm not a webforms expert, but I believe the page stores a reference to each control present in the page.
You can think of webforms like an n-ary tree... each control has a parent and can have 0 to many children. So, if these are static controls you should just be able to grab a reference to their parent and iterate over that... with no need for the children's ids.
Also, you can query for children based on their id... something like myControl["myID1"] so you can concat the number with the string and get the control that way.
Lastly, if these are purely dynamic controls, i.e. you don't know how many there are, just store references to them in an ordered collection and iterate over them that way.
EDIT:
Here we go:
WebControl myControl;
myControl.Controls.Add(someControlReference);
Then, to grab a control by ID:
WebControl someControl = myControl.FindControl("someControlID1");
From there you can do like:
string a = someControl.Text

previouspage.findcontrol getting variable from previous page

i am trying to retain the value of a variable from a previous page. i believe this is the C# way to do this, but i would like the vb.net way can someone please help:
TextBox myTxt = (TextBox)Page.PreviousPage.FindControl("previousPageTextBox");
currentPageTextBox.text = myTxt.Text;
i would like to know how to code this in vb.net
i tried this:
Dim myTxt As TextBox = CType(Page.PreviousPage.FindControl("Textbox1"), TextBox)
TextBox1.Text = myTxt.Text
but i got this error msg:
use the new keyword to create an object instance
This should do it, also make sure you are using Server.Transfer to go between pages.. but I am sure you already know this:
Dim myTxt as TextBox = CType(Page.PreviousPage.FindControl("previousPageTextBox"), TextBox)
currentPageTextBox.text = myTxt.Text
dim txt as TextBox =CType( Page.PreviousPage.FindControl("previousPageTextBox"),
TextBox)
currentPageTextBox.Text = txt.Text
PS:- You need to set the previous page in the page where you want to find the control.
<%# PreviousPageType VirtualPath="~/Test.aspx" %>
Also better way will be to create an function on previous page which returns the text in textbox.
internal function TextBoxText() as string
return myTextPage.Text
end function
and use this on next page like this:
currentPageTextbox.Text = Page.PrevousPage.TextBoxText
let me know if this works because I've not used vb for long long time.
PPS:- It is only available if you user Server.Transfer or go to currentPage using some asp.net contorl like LinkButton from simple href links PreviousPage is null

"Both DataSource and DataSourceID are defined" error using ASP.NET GridView

"Both DataSource and DataSourceID are defined on 'grdCommunication'. Remove one definition."
I just got this error today, the code has been working until this afternoon I published the latest version to our server and it broke with that error both locally and on the server. I don't use "DataSourceID", the application reads database queries into a datatable and sets the datatable as the DataSource on the GridViews. I did a search in Visual Studio, searching the entire solution and the string "DataSourceID" does not appear in even 1 line of code in the entire solution. This is the first thing that freaked me out.
I figure it had been working yesterday, so I reverted the code to yesterday's build. The error was still there. I kept going back a build, and still the issue is there. I went back a month, I am still getting the same error. This application was working fine this morning? There has really been no code changes, and no where in the application is the DataSourceID EVER set on any of the gridviews. Has anyone ever seen anything like this at all??
How can I get that error if DataSourceID is never set... and the word "DataSourceID" is not in my solution? I just did a wingrep on the entire tree doing a case insensitive search on datasourceid.... pulled up absolutely nothing. That word is absolutely no where in the entire application.
<asp:GridView ID="grdCommunication" runat="server"
Height="130px" Width="100%"
AllowPaging="true" >
... standard grid view column setup here...
</asp:GridView>
// Code behind.. to set the datasource
DataSet dsActivity = objCompany.GetActivityDetails();
grdCommunication.DataSource = dsActivity;
grdCommunication.DataBind();
// Updated: removed some confusing notes.
Try this:
DataSet dsActivity = objCompany.GetActivityDetails();
grdCommunication.DataSource = dsActivity.Tables[0];
grdCommunication.DataBind();
Holy smoke batman. The Table name was changed causing my Datasource to be no good. But that error message doesn't make any sense in this situation. So technically tsilb's solution will work if I call the table by index instead of by name, so I'll mark his solution as correct.
After reading his post, I tried dsActivity.Tables["Activities"] instead of passing the dataset to the Datasource and the table name to the Datamember, and obviously that didn't work, but If I pass the actual index, which I don't like doing because that index might change, then it is now working. But the messed up part, was that error.. That error was completely off base as to what the problem was. saying that I defined both and to remove one, when in reality, that was not the case. and another really messed up thing, was the table name was only changed to be all upper case... But hey, "Activities" is a different key than "ACTIVITIES".
Replace this code before this grdCommunication.DataSource = dsActivity;
grdCommunication.DataBind();
grdCommunication.DataSourceID="";
tslib is right, don't do:
grdCommunication.DataSourceID = null;
or the string.Empty version. You only use the DataSourceID if you're using a SqlDataSource or ObjectDataSource control for your binding.
It's called "declarative" binding because you're using "declared" controls from on your page. Binding to controls does not require a call to the DataBind() method.
Because you're DataBinding manually (calling grd.DataBind()) you only set the DataSourrce and then call DataBind().
I ran into the same error, but a totally different problem and solution. In my case, I'm using LINQ to SQL to populate some dropdown lists, then caching the results for further page views. Everything would load fine with a clear cache, and then would error out on subsequent page views.
if (Cache["countries"] != null)
{
lbCountries.Items.Clear();
lbCountries.DataValueField = "Code";
lbCountries.DataTextField = "Name";
lbCountries.DataSource = (Cache["countries"]);
lbCountries.DataBind();}
else
{
var lstCountries = from Countries in db_read.Countries orderby Countries.Name select Countries;
lbCountries.Items.Clear();
lbCountries.DataValueField = "Code";
lbCountries.DataTextField = "Name";
lbCountries.DataSource = lstCountries.ToList();
lbCountries.DataBind();
Cache.Add("countries", lstCountries, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 240, 0), System.Web.Caching.CacheItemPriority.High, null);
}
The issue came from:
Cache.Add("countries", lstCountries, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 240, 0), System.Web.Caching.CacheItemPriority.High, null);
When it should have been:
Cache.Add("countries", lstCountries.ToList(), null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 240, 0), System.Web.Caching.CacheItemPriority.High, null);
I got this error today, turns out that it had nothing to do with DataSourceID, and had everything to do with the DatasSource itself.
I had a problem in my DatasSource , and instead of getting a DatasSource related error, I got this meaningless error.
Make sure you're DatasSource is good, and this error should go away.
always bind dataset with table index to gridview...
ex. gridgrdCommunication.Table[0]; as metioned above by Tsilb
second way you intentionally write..
gridgrdCommunication.DataSourceID = String.Empty;
gridgrdCommunication.DataSource=ds;
gridgrdCommunication.DataBind();
Check you database structure.... if you are acceding your data throw a dbml file, the table structure in your database it's different of the dbml file structure
If you are using the Object Data Source and want to conditionally reload the grid in code behind you can successfully do this:
Dim datatable As DataTable = dataset.Tables(0)
Dim dataSourceID As String = gvImageFiles.DataSourceID
gvImageFiles.DataSourceID = Nothing
gvImageFiles.DataSource = datatable.DefaultView
gvImageFiles.DataBind()
gvImageFiles.DataSource = Nothing
gvImageFiles.DataSourceID = dataSourceID
You need to chose one way to bind the grid
if it is from code behind means using c# code then remove the datasourceid property from grid view from design view of grid
like this
//you have to make it like this
Please try this:
gvCustomerInvoiceList.DataSourceID = "";
gvCustomerInvoiceList.DataSource = ci_data;
gvCustomerInvoiceList.DataBind();
I got this error today. It turns out that my stored procedure did not return neither any record nor a structure. This was because I had an empty try catch without a raiserror.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Page.DataBind()
End Sub
Function GetData()
Dim dt As New DataTable
Try
dt.Columns.Add("ROOM_ID", GetType(String))
dt.Columns.Add("SCHED_ID", GetType(String))
dt.Columns.Add("TIME_START", GetType(Date))
dt.Columns.Add("TIME_END", GetType(Date))
Dim dr As DataRow = dt.NewRow
dr("ROOM_ID") = "Indocin"
dr("SCHED_ID") = "David"
dr("TIME_START") = "2018-01-03 09:00:00.000"
dr("TIME_END") = "2018-01-03 12:00:00.000"
dt.Rows.Add(dr)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Return dt
End Function
and add this to your item DataSource="<%# GetData() %>"
In my case the connection string to the database was not working. Fixing the connection string got rid of this error.

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