ASP NET Dropdown box in a user control losing viewstate - asp.net

I have a usercontrol in an ASP NET web application on which I create dropdown lists based on some loaded data (from an XML file via a component in the BIN directory)
I found that I couldn't retrieve the values across postbacks, and I've been doing a fair bit of reading to figure out why. What I would like someone to explain is why the following condition exists:
Dim dd As New DropDownList
With dd
.Items.Add(New ListItem("First Item"))
.Items.Add(New ListItem("Second Item"))
.Items.Add(sts(0))
.Items.Add(sts(1))
.Items.Add(sts(2))
.Items.Add(New ListItem("Third Item"))
End With
AddHandler dd.SelectedIndexChanged, AddressOf changed
divControls.Controls.Add(dd)
In the code above the three items 'First Item', 'Second Item' and 'Third Item' all behave correctly, as you can see they are added directly to the dropdown box in code. The items sts(0), sts(1) and sts(2) are all loaded from an XML file into either an array or list of string
Interestingly, sts(0) always posts back correctly, but any subsequent items which are added from the dynamic source don't. I've tried a bunch of ways of getting my list of strings into the dropdown so that they are still there upon postback but I'm not having much luck, would be most grateful if anyone could shed some understanding on this

I figured it out - I need to give each ListItem a value, I had lazily coded just the text portion since I wasn't using ordinals in the list, but ASP NET needed the ordinal value, or the list item value, to register the item for event validation, I expect ASP NET was only able to give subsequent items in the array or list of string the same ordinal or listitem value as all the other members of the collection, since they are from the same object. Works now!

Related

A list(of String) I have fails to populate on a post back but populates just fine on the initial page load

I am relatively new to programming so please bare with me if I use improper terminology for the question I am about to ask.
Currently, I have a list(of String) that I am populating with 2 values that I am pulling from a database. Code Below.
objCn.Open()
sqlTermSelect.Connection = objCn
sqlTermSelect.CommandText = "Select PartsTerm, LaborTerm FROM SKU INNER JOIN Agreement On SKU.SKU = Agreement.SKU WHERE Agreement = #Agreement"
sqlTermSelect.Parameters.Add("#Agreement", SqlDbType.VarChar, 50).Value = txtAgreement.Text
Dim termDA As New SqlDataAdapter(sqlTermSelect)
Dim termDT As New DataTable()
termDA.Fill(termDT)
For i As Integer = 0 To termDT.Rows.Count - 1
listValues.Add(termDT.Rows(i)("PartsTerm").ToString())
listValues.Add(termDT.Rows(i)("LaborTerm").ToString())
Next
objCn.Close()
I am then storing the values of this list in two variables that I use as checks to see whether certain controls on my page should be enabled/visible or disabled/invisible.
The page that this is affecting operates(for lack of a better word) in two ways, the first is a brand new page with empty controls that the user fills out. The second way is if the user begins to fill out the page and leaves, the data they filled out is saved and they can return later to continue filling it out (I am not 100% certain but I believe when a user returns to an "in progress" page it is a post back, I could be wrong, I'm not terribly sure how this is handled).
The problem I am having comes to when this list is populated with the database values. When I go to a brand new page, the list is populated and the controls mentioned above are enabled/disabled appropriately with no issues, the issue arises when I go to an "in progress" page the list values don't populate and the controls that should be disabled are enabled. Essentially, I am looking for a way to populate this list every time a page is opened, "in progress" or brand new. The code above that populates the list is in the PageLoad() event and I have verified that it is not in a "If Not IsPostBack" statement.
Any and all help would be greatly appreciated, if there is anything I should add to this post code related I would be more than happy to supply it.

Reading a DataSet in JavaScript

' USED TO REFRESH THE PAGE WHIN IT IS POSTED BACK
If (IsPostBack = False) Then
' USED TO DISPLAY DEFAULT FIRST ITEM IN THE DROPDOWN
Dim Li1 As New ListItem()
Li1.Text = "ALL"
Li1.Value = ""
cboStudy.Items.Add(Li1)
' USED TO COUNT THE STUDIES IN THE DROPDOWN
If (objDS.Tables(0).Rows.Count <> 0) Then
' USED TO CIRCULATE LOOP UPTO THE RECORD COUNT
Dim i As Integer
For i = 0 To objDS.Tables(0).Rows.Count - 1
' USED TO CREATE NEW ITEM IN THE DROPDOWN
Dim Li As New ListItem
Li.Text = objDS.Tables(0).Rows(i)("Study_Desc").ToString()
Li.Value = objDS.Tables(0).Rows(i)("Study_ID").ToString()
'USED TO ADD ITEMS IN THE DROPDOWN
cboStudy.Items.Add(Li)
Next
End If
'USED TO SAVE THE CHANGES IN DATASET
objDS.AcceptChanges()
' USED TO CLOSE THE DATABASE CONNECTION
objDS.Dispose()
End If
End If
I have to read dataset in javascript. So that I have to bind Study_Desc in DropDownList.
How can I do that?
I believe you might find it useful to review how an ASP.NET page works and how it renders. In your particular case you are setting the contents of a dropdownlist to your dataset. This will then render a 'select' object to the user with the appropriate entries without the need for Javascript. This all occurs on the server-side, which is processed on the server before a HTML response to given back to the user.
With Javascript, this code runs on the client-side, i.e. the user's computer. Here it is possible to retreive your dataset (by this, the dataset will get serialised to be passed over the wire and read into a format that Javascript can read) and have it interact on the client-side. The question is, in your case, is why bother as you're rendering the dropdown on the server-side. If you are interested in pushing your dataset to Javascript, check out the links on this post for a selection of approaches you can take.
Minor notes:
In your code you're using the 'AcceptChanges' method when there is absolutely no reason to use this unless you're making a change(s) to the dataset which I'm guessing you're not in the PageLoad...

Iteratively Reference Controls by Name Pattern (VB.NET)

Is there a way to iteratively reference an ASP.NET control based on it's name pattern? Perhaps by a "pointer" or something?
What I have are a large set of comboboxes (each with an associated DropDownList and TextBox control). The DropDownList always has an item selected by default, but the use may wish to submit a NULL value. I come up with the following code to handle three cases: NULL, Existing Item, New Item.
'TextBoxControl & DropDownListControl should iteratively reference their
' respective TextBox & DropDownList controls by the actual control name
If StrComp(TextBoxControl.Text, DropDownListControl.SelectedItem.ToString) = 0 Then
'When an Existing Item is selected, Do Something
ElseIf Not TextBoxControl.Text = "" Then
'When a New Item is entered, Validate & Do Something
Else
'When NULL, Do Something
End If
The problem is, with so many comboboxes, I could easily end up with hundreds of lines of code. I wish to handle this in a more dynamic way, but I do not know if it is possible to reference controls in this way. Say I wanted to reference all the TextBox Controls and DropDownList Controls, respectively.
I can do string formatting with a given naming pattern to generate a name ID for any of the controls because they are all named with the same pattern. For example by attaching a specific suffix, say "_tb" for TextBox Controls and "_ddl" for DropDownList Controls:
Left(item.SelectedItem.ToString, item.SelectedItem.ToString.Length - 3) + "_tb"
Can this sort of thing be done in VB? Ultimately, my goal is to take the value entered/selected by the user, if any, and send it to a stored procedure on SQL Server for insertion into the database.
Yes. Write your code inside of a function having parameters for the textbox and the dropdown, and then write the function in terms of those two parameters. Then you simply call that function for every set instead of copy/pasting code everywhere.
Don't attempt choosing things by name. That's fragile and imposes machine requirements on a field that'd designed for human consumption.
I am not sure if the samething that applies VBA will apply to your situation, but I had the same issue and was able to use:
Me.MultiPage1.Pages(1).Controls("ref" & i + 1).Value
where controls encompasses all controls on the userform ("Me"). So if the controls in your program conform to a consecutive naming structure it is easy handle if the above applies vb.net

how do I reference the values from textboxes on form submit that reside in my usercontrol? ASP.NET(VB)

I can't believe I couldn't find an answer to this question after literally hours of searching the web. Is this so basic that everyone just knows how to do this? As you might have guessed I'm new to asp.net(vb).
My situation:
I have a large form that reuses several elements, so I decided to create a usercontrol with some common fields. The problem is when the form is filled out by a user and submitted, how do I reference those values so I can input them to my database???
Example:
Using Conn As New SqlConnection(connect)
Using Cmd As New SqlCommand(SQL, Conn)
Cmd.Parameters.AddWithValue("#Acct_Company", txtPartner.Text)
Cmd.Parameters.AddWithValue("#Acct_AccountNum", txtPartnerAccount.Text)
So, above two Cmd lines are for normally inserted textboxes in my form, but what would the line look like to reference any usercontrol form fields?
Any help would be greatly appreciated.
You need to expose the controls some how to the page that contains the user control. One way to to this is like this (within the control code):
Property CompanyName As String
Get
Return txtPartner.Text
End Get
Set(value As String)
txtPartner.Text = value
End Set
End Property
Then, the page containing the user control can access the value like this:
myControl.CompanyName

Webcombo return error when trying to populate based on another WebCombo

This has gotten me completely frustrated
I have a few webcombo boxes that are hierachial:
Continent
Country
When the form loads everything works fine, when I change the continent the first time, the country repopulates correctly. However if I change the continent a second time I receive an error:
Specified argument was out of the range of valid values.Parameter name: The DataValueField of ValueField was not found in the Columns collection.
Can anyone tell me why?
P.S. This is all I have in the Page_Load event
if (!IsPostBack)
{
this.Load_AreaList();
this.Load_AreasOfInterest();
this.Load_Degrees();
this.Load_GenderList();
this.Load_ParticipationDateModifiers();
this.Load_ProgramCategories(nEventID);
this.Load_YesNoList();
this.Load_ParticipantInformation(nParticipantID);
}
Also this happens in another part of the form with another Country webcombo which is supposed to populate a state combo box.
In many cases, columns in database tables return null when no value is stored in that column. However, a null value can present challenges when you are working with ASP.NET code or with data-bound Web controls. For example, an exception is thrown if you try to bind the SelectedValue of a DropDownList control to null. If this is not the case change AppendDataBoundItems property. The AppendDataBoundItems property allows you to add items to the ListControl object before data binding occurs. After data binding, the items collection contains both the items from the data source and the previously added items.
Let me know if it works...
s

Resources