Renumber all records when one is updated - ms-access-2010

I am using Access 2010. I have a datasheet form called Projects with two fields, [Project Name] and [Priority]. I would like to be able to update the priority number for one of the records and have all other priority numbers update automatically. For example, Project Red is priority 1. Project Orange is Priority 2 and Project Blue is Priority 3. If I update Blue to number 1, I would like Red to update to 2 and Orange to update to 3. Is this possible?
Projects Form

That is possible.
Use the AfterUpdate event of the textbox with Priority:
Private Sub Priority_AfterUpdate()
Dim rst As DAO.Recordset
Dim lngId As Long
Dim lngPriorityNew As Long
Dim lngPriorityFix As Long
' Save record.
Me.Dirty = False
' Prepare form.
DoCmd.Hourglass True
Me.Repaint
Me.Painting = False
' Current Id and priority.
lngId = Me!Id.Value
lngPriorityFix = Nz(Me!Priority.Value, 0)
If lngPriorityFix <= 0 Then
lngPriorityFix = 1
Me!Priority.Value = lngPriorityFix
Me.Dirty = False
End If
' Rebuild priority list.
Set rst = Me.RecordsetClone
rst.MoveFirst
While rst.EOF = False
If rst!Id.Value <> lngId Then
lngPriorityNew = lngPriorityNew + 1
If lngPriorityNew = lngPriorityFix Then
' Move this record to next lower priority.
lngPriorityNew = lngPriorityNew + 1
End If
If Nz(rst!Priority.Value, 0) = lngPriorityNew Then
' Priority hasn't changed for this record.
Else
' Assign new priority.
rst.Edit
rst!Priority.Value = lngPriorityNew
rst.Update
End If
End If
rst.MoveNext
Wend
' Reorder form and relocate record.
Me.Requery
Set rst = Me.RecordsetClone
rst.FindFirst "Id = " & lngId & ""
Me.Bookmark = rst.Bookmark
' Present form.
Me.Painting = True
DoCmd.Hourglass False
Set rst = Nothing
End Sub

Related

Retrieving values from dynamically created controls

First post, so go easy on me.
I've been coding for years, first with VB6, then VB.NET and more recently ASP.NET. I'm ashamed to say, this issue has beaten me to the point where I need to ask for help. What's more annoying is that this should be a simple thing to achieve! I'm clearly missing something here.
I'm creating checkbox controls dynamically, quite a few of them in fact. Two per dynamically created table row and their IDs are appended with the ID of the particular DB record on the row, row 1, 2, 3 etc. So on each row there would be two checkboxes, ihave_check_1, ineed_check_1. The next row would be ihave_check_2 and ineed_check_2 and so on.
There is a submit button at the bottom of the page, and when clicked, it's supposed to loop through each row (and cell) in the table and pick out controls whose IDs contain "ihave_check_" and "ineed_check_" then get their Checked value. Once I have the values, I add a record into the database.
Problem is, when you click the button, the table disappears and so do the values.
From what I've read so far, this is happening because the controls are dynamically created, if they were static (coded in the HTML section) I wouldn't have this problem.
So first question, what do I need to do to get it working?
And second question, why is using dynamic controls so difficult?
Here's the code setting up the table, which works great:
Private Sub ddCardSeries_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ddCardSeries.SelectedIndexChanged
If IsPostBack = True And Not ddCardSeries.SelectedValue = "Select..." Then
cardsTable.Visible = True
Dim dat As New DataLayer3.DataConnector
dat.DataConnector("Provider=SQLOLEDB;Server=192.XXX.XXX.XXX;Database=GPKDB;User Id=sa;Password=XXXXXXXXXXX;")
Dim dtSections As New DataTable
dtSections = dat.DataSelect("SELECT baseCardID,baseCardSeries,baseCardNumber,baseCardName,frontArtist,conceptArtist,backArtist,backWriter,isBaseCard,isDieCut,isMatte,isGlossy,differentBack,frontImage,backImage FROM baseCards where baseCardSeries = '" & Split(Split(ddCardSeries.Text, "(ID:")(1), ")")(0) & "' and isBaseCard = 'Yes'")
If dtSections.Rows.Count > 0 Then
For i As Integer = 0 To dtSections.Rows.Count - 1
Dim row As New TableRow
For x = 0 To dtSections.Columns.Count - 1
Dim cell1 As New TableCell
If Not IsDBNull(dtSections.Rows(i)(x)) Then
If x = 0 Then
cell1.Text = dtSections.Rows(i)(x)
ElseIf x = 1 Then
cell1.Text = get_card_series(dtSections.Rows(i)(x))
ElseIf x = 13 Then
cell1.Text = "<img src='" & dtSections.Rows(i)(x) & "' height='120'"
ElseIf x = 14 Then
cell1.Text = "<img src='" & dtSections.Rows(i)(x) & "' height='120'"
Else
cell1.Text = dtSections.Rows(i)(x)
End If
Else
cell1.Text = ""
End If
row.Cells.Add(cell1)
Next x
Dim newbutton As New Button
Dim newlabel As New Label
newlabel.Text = "<br />"
newbutton.Text = "Modify this entry"
newbutton.Width = 120
newbutton.ID = "modify_button_" & dtSections.Rows(i)(0)
Dim newcheck1 As New CheckBox
Dim newlabel2 As New Label
newlabel2.Text = "<br />"
newcheck1.Text = "I own this card"
newcheck1.Width = 120
newcheck1.ID = "ihave_check_" & dtSections.Rows(i)(0)
Dim newcheck2 As New CheckBox
newcheck2.Text = "I need this card"
newcheck2.Width = 120
newcheck2.ID = "ineed_check_" & dtSections.Rows(i)(0)
Dim cell2 As New TableCell
If is_user_admin() = True Then
newbutton.Enabled = True
Else
newbutton.Enabled = False
End If
cell2.Controls.Add(newbutton)
cell2.Controls.Add(newlabel)
cell2.Controls.Add(newcheck1)
cell2.Controls.Add(newlabel2)
cell2.Controls.Add(newcheck2)
row.Cells.Add(cell2)
cardsTable.Rows.Add(row)
Next
End If
Else
cardsTable.Visible = False
End If
End Sub
Here's the code that loops through the table and tries to save the results to the database:
Protected Sub SubmitChanges_Click(sender As Object, e As EventArgs) Handles SubmitChanges.Click
For Each pcontrol As control In Page.Controls
Dim havecard As String = Nothing
Dim needcard As String = Nothing
Dim rowcardid As String = Nothing
'For Each tabcell As TableCell In tabrow.Cells
'For Each pgcontrol As Control In tabcell.Controls
If TypeOf pcontrol Is CheckBox And Split(pcontrol.ID, "_")(0) = "ihave" Then
rowcardid = Split(pcontrol.ID, "_")(2)
Dim chkbox As CheckBox = pcontrol
If chkbox.Checked = True Then
havecard = "Yes"
Else
havecard = "No"
End If
End If
If TypeOf pcontrol Is CheckBox And Split(pcontrol.ID, "_")(0) = "ineed" Then
rowcardid = Split(pcontrol.ID, "_")(2)
Dim chkbox As CheckBox = pcontrol
If chkbox.Checked = True Then
needcard = "Yes"
Else
needcard = "No"
End If
End If
'Next
If Not havecard = Nothing And Not needcard = Nothing Then
If add_card_to_user_list(Session("username"), rowcardid, havecard, needcard) = True Then
Label1.Text = "Update complete"
Else
Label1.Text = "Update failed"
End If
End If
'Next
Next
End Sub
Public Function add_card_to_user_list(ByVal userid As String, ByVal cardid As String, ByVal own As String, ByVal need As String) As Boolean
Try
Dim dat As New DataLayer3.DataConnector
dat.DataConnector("Provider=SQLOLEDB;Server=192.XXX.XXX.XXX;Database=GPKDB;User Id=sa;Password=XXXXXXXX;")
Dim dtCardSeries As New DataTable
dtCardSeries = dat.DataSelect("select CardID from [" & userid & "_cards] where cardid = '" & cardid & "'")
If dtCardSeries.Rows.Count > 0 Then
dat.DataDelete("delete from [" & userid & "_cards] where cardid = '" & cardid & "'")
End If
dat.DataInsert("insert into [" & userid & "_cards] (Username,CardID,Own,Need) values ('" & userid & "', '" & cardid & "', '" & own & "', '" & need & "');")
Return True
Catch ex As Exception
Return False
End Try
End Function
Any help at this point would be gratefully received.
Thanks!

Arrays and variables clears itself after a end sub in VB.net

I am writing a times tables program in ASP.net and I need some help. The problem I am experiencing is that when the button sub ends and the screen pops up again for user input, all the arrays and variables are now set to nothing or 0.
Is there are way to keep all the values for variables after a sub ends and to use them later on?
Any help will be appreciated.
Public Class PickTimesTables
Inherits System.Web.UI.Page
Dim count As Integer = 0
Dim NumberQ As Integer
Dim RandomN As Integer
Dim FirstNumber() As Integer
Dim FirstNumberTemp() As Integer
Dim SecondNumber() As Integer
Dim correctAnswers As Integer
Dim inc As Integer = 0
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
PanelQuestion.Visible = False
PanelAnalysis.Visible = False
End Sub
Protected Sub btnTest_Click(sender As Object, e As EventArgs) Handles btnTest.Click
PanelQuestion.Visible = True
lblOperator.Text = "X"
If chktimes1.Checked = False And chktimes2.Checked = False And chktimes3.Checked = False And chktimes4.Checked = False And chktimes5.Checked = False And chktimes6.Checked = False And chktimes7.Checked = False And chktimes8.Checked = False And chktimes9.Checked = False And chktimes10.Checked = False And chktimes11.Checked = False And chktimes12.Checked = False Then
MsgBox("Pick a Times Table to be Tested for..")
ElseIf txtNoQuestion.Text = "" Then
MsgBox("Pick the Number of Question for the test")
Else
NumberQ = txtNoQuestion.Text
count = 0
If chktimes1.Checked Then
count = count + 1
End If
If chktimes2.Checked Then
count = count + 1
End If
If chktimes3.Checked Then
count = count + 1
End If
If chktimes4.Checked Then
count = count + 1
End If
If chktimes5.Checked Then
count = count + 1
End If
If chktimes6.Checked Then
count = count + 1
End If
If chktimes7.Checked Then
count = count + 1
End If
If chktimes8.Checked Then
count = count + 1
End If
If chktimes9.Checked Then
count = count + 1
End If
If chktimes10.Checked Then
count = count + 1
End If
If chktimes11.Checked Then
count = count + 1
End If
If chktimes12.Checked Then
count = count + 1
End If
If txtNoQuestion.Text = 0 Then
MsgBox("You cannot have a test with 0 Questions")
Else
ReDim FirstNumberTemp(count - 1)
For i = 0 To count - 1
If chktimes1.Checked Then
FirstNumberTemp(i) = 1
chktimes1.Checked = False
ElseIf chktimes2.Checked Then
FirstNumberTemp(i) = 2
chktimes2.Checked = False
ElseIf chktimes3.Checked Then
FirstNumberTemp(i) = 3
chktimes3.Checked = False
ElseIf chktimes4.Checked Then
FirstNumberTemp(i) = 4
chktimes4.Checked = False
ElseIf chktimes5.Checked Then
FirstNumberTemp(i) = 5
chktimes5.Checked = False
ElseIf chktimes6.Checked Then
FirstNumberTemp(i) = 6
chktimes6.Checked = False
ElseIf chktimes7.Checked Then
FirstNumberTemp(i) = 7
chktimes7.Checked = False
ElseIf chktimes8.Checked Then
FirstNumberTemp(i) = 8
chktimes8.Checked = False
ElseIf chktimes9.Checked Then
FirstNumberTemp(i) = 9
chktimes9.Checked = False
ElseIf chktimes10.Checked Then
FirstNumberTemp(i) = 10
chktimes10.Checked = False
ElseIf chktimes11.Checked Then
FirstNumberTemp(i) = 11
chktimes11.Checked = False
ElseIf chktimes12.Checked Then
FirstNumberTemp(i) = 12
chktimes12.Checked = False
End If
Next
ReDim FirstNumber(NumberQ - 1)
For i = 0 To NumberQ - 1
Randomize()
RandomN = FirstNumberTemp(Int(Rnd() * count))
FirstNumber(i) = RandomN
Next
ReDim SecondNumber(NumberQ - 1)
For i = 0 To NumberQ - 1
Dim rn As New Random(Now.Millisecond)
RandomN = rn.Next(1, 13)
SecondNumber(i) = RandomN
Next
lblFirstN.Text = FirstNumber(0)
lblSecondN.Text = SecondNumber(0)
End If
End If
End Sub
Protected Sub txtInput_TextChanged(sender As Object, e As EventArgs) Handles txtInput.TextChanged
NumberQ = txtNoQuestion.Text
If txtInput.Text = FirstNumber(inc) * SecondNumber(inc) Then
lblFirstN.Text = FirstNumber(inc + 1)
lblSecondN.Text = SecondNumber(inc + 1)
correctAnswers = correctAnswers + 1
txtInput.BackColor = Drawing.Color.Green
Else
txtInput.BackColor = Drawing.Color.Red
lblFirstN.Text = FirstNumber(inc + 1)
lblSecondN.Text = SecondNumber(inc + 1)
End If
End Sub
End Class
This is a common mistake for newcomers to ASP.Net Webforms. There is this idea that your page class instance lives for an entire session, for all of a user's interactions with the page in the browser. This does not happen. Any interaction with your page that causes an event to fire creates a new postback from the client to the server, and every postback uses a brand new instance of the Page class. By the time the user sees your page in their browser, whatever Page object you used to render the html for that view has already been destroyed and garbage collected.
There are some things you can do to get around this, like putting variables in the Session, URL, or ViewState, but often you need to completely re-think your approach to something that is more natural for a web site.
Additionally, you'll want to re-think handling a TextChanged event in your VB.Net code. Generally speaking, TextChanged events need to return to the user in 25-40 milliseconds, or the view will feel extremely sluggish. It's not usually a problem when the program is running right there on the user's computer, and has all the memory and CPU power of that workstation available. It's a whole other story for web sites, where you might have an 80ms delay before the request even reaches the server and another 80ms for the response, all before doing any processing, and the server is sharing it's CPU and memory resources to support as many users as you can fit.
Instead, look into using a javascript event for that processing, and only validate the text in your VB.Net code when the user finally tries to submit or save the end result.
Finally, those calls to the MsgBox() function need to go, too. It only seems to work on your system because your web server is on the same machine as the web browser. When you go to actually put this on a real server and test from a different place, those message will display on the server, not in the user's web browser.
They'll all be reset because that's the stateless nature of the web. They don't keep their values because each subsequent time you view that page (or step through it using the debugger), it's a new request.
You should google storing asp.net variables in ViewState or Session, i.e. ViewState-backed properties.

Dynamically Adding data to jagged array?

I have a recursive function that creates a list of items based on their hierarchy(integer is used to determine which level 1 to 10 max). There can be x number of items in any given level. I want to store all the items that belong the same level at the corresponding index of the jagged array. The items aren't retrieved based on their level so the level can be jumping around all of over the place as the function recurses.
Function RecurseParts(lngPartID1, lngLevel) As Object
'this function will recursivley print the parts lists for the part ID passed in
If IsNumeric(lngPartID1 & "") Then
Dim objRSTemp As Object = Server.CreateObject("ADODB.Recordset")
objRSTemp.CursorLocation = adUseClient
objRSTemp.Open(PART_LIST_SQL & lngPartID1, objConn, adOpenForwardOnly, adLockReadOnly)
'objRSTemp.ActiveConnection = Nothing
If objRSTemp.eof And objRSTemp.bof Then
'PROBLEM, WE HAVE NO RECORDS
Response.Write("There Were No Parts For This Assembly (Part ID #:" & lngPartID1 & ")")
Else
'make output
Dim strTemp As String = String.Empty
If lngLevel <> 1 Then strTemp = " style=""display: none;"">"
Response.Write("<table id='tblparts" & lngCurrentLineNum & "' border=""0"" cellspacing=""0"" width=""100%"" cellpadding=""1"" " & strTemp)
Do Until objRSTemp.EOF
'increase the current line num
lngCurrentLineNum = lngCurrentLineNum + 1
'get current Part ID
lngCurrentPartID = objRSTemp("PartID").value
'reset flag
blnIsAssm = False
'loop thru array of assemblies to see if this is a parent
For ctr = 0 To UBound(arrAssmList, 2)
If arrAssmList(0, ctr) = lngCurrentPartID Then
'the current part is an assembly
blnIsAssm = True
Exit For
ElseIf arrAssmList(0, ctr) > lngCurrentPartID Then
Exit For
End If
Next
If blnIsAssm Then
'recurse these parts
If RecurseParts(objRSTemp("PartID").value, lngLevel + 1) = True Then
'awesome
End If
End If
objRSTemp.MoveNext()
Loop
Response.Write("</table>")
End If
If objRSTemp.State Then objRSTemp.Close()
objRSTemp = Nothing
'RETURN FUNCTION
RecurseParts = True
Else
'no PART ID passed in
Response.Write("No Part ID Passed In")
RecurseParts = False
End If
End Function
It sounds like a Dictionary would work here.
Dim myDict As New Dictionary(Of Integer, List(Of String))
In your recursive function. The parts in the {} are the parts you have to supply.
'this builds the keys as you go
If Not myDict.ContainsKey({{key} -> your Integer}) Then
'add key and use the From statement to add a value if know at this time
myDict.Add({key}, New List(Of String) From {value})
Else
myDict({key}).Add({string to insert at this level})
End If
List of keys in reverse order:
Dim keys = myDict.Keys.OrderByDescending(Function(k) k)
I was able to create a List to store all the partIDs and their levels.
Dim arrSubID As New List(Of List(Of Integer))()
Function RecurseParts(paramenters)
For ctr = 0 To UBound(arrAssmList, 2)
If arrAssmList(0, ctr) = lngCurrentPartID Then
'checks whether we need a new index in the list
If lngLevel + 1 > arrSubID.Count Then
arrSubID.Add(New List(Of Integer))
End If
'adds the partID where it belongs!
arrSubID(lngLevel).Add(lngCurrentPartID)
blnIsAssm = True
Exit For
ElseIf arrAssmList(0, ctr) > lngCurrentPartID Then
Exit For
End If
Next
End Function

If today's date minus db date is less than 48 hours, do something but I am getting an error. Any ideas?

Sorry again, experts for the bother again.but
We have a db date called orderdate.
If today's date - orderdate is less than 2 days (or 48 hours), disable Cancel Order button so user cannot cancel his or her order.
When I tried running the following code, I get Input string not in the format
Orderdate is of type datetime. However, we would like to display the date in the format of MM/dd/yyyy. Example: 6/4/2013, not 06/04/2013.
Can you please look at my code and tell me what I am doing wrong?
If dr1.Read() Then
Dim odate As String = DateTime.Parse(dr1("orderDates").ToString()).ToShortDateString()
Dim cancelBtn As New Button()
Dim dates As String = DateTime.Parse(Now().ToString()).ToShortDateString()
If (sdate - dates) <2 Then
cancelBtn.Enabled = False
Else
cancelBtn.Enabled = True
End If
End If
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
' Create cancel training button
Dim cancelBtn As New Button()
cancelBtn.Style.Add("width", "105px")
cancelBtn.Style.Add("padding", "5px")
cancelBtn.Style.Add("margin", "5px")
'cancelBtn.Enabled = False
cancelBtn.Text = "Cancel training"
If e.Row.RowIndex > "-1" Then
' Change tracking ID to link
'Dim track As [String] = e.Row.Cells(4).Text
'If track <> " " AndAlso track.Length > 0 Then
' Dim trackLink As New Literal()
' trackLink.Text = "<a style='color: blue;' href='" + track + "'/>Track</a>"
' e.Row.Cells(4).Controls.Add(trackLink)
'End If
' Add buttons to column
Dim oid As [String] = e.Row.Cells(0).Text
Dim invoiceLink As New Literal()
invoiceLink.Text = "<a style='color: blue;' href='Invoice.aspx?oid=" + oid + "'/>" + oid + "</a>"
e.Row.Cells(0).Controls.Add(invoiceLink)
e.Row.Cells(e.Row.Cells.Count - 1).Controls.Add(cancelBtn)
' Pass order id & row to on-click event
'cancelBtn.Click += new EventHandler(this.cancelBtn_Click);
'cancelBtn.CommandArgument = e.Row.RowIndex + "-" + oid
End If
End Sub
I'm not sure why you'd want to convert your date fields into strings. I would recommend leaving those as datetime objects for your comparison. You can always manipulate the display of the dates in your presentation logic.
This is some working code leaving as dates using Subtract and TotalDays:
Dim cancelBtn As New Button()
Dim odate As DateTime = DateTime.Parse(dr1("orderDates").ToString())
Dim dates As DateTime = DateTime.Now()
If dates.Subtract(odate).TotalDays >= 2 Then
cancelBtn.Enabled = False
Else
cancelBtn.Enabled = True
End If
You could also consolidate the If statement to a single line:
cancelBtn.Enabled = dates.Subtract(odate).TotalDays < 2
EDIT: Regarding the logic, your DB field orderDates sounds like it refers to the day the order was created. That date will always be in the past, so we would be interested in Today - orderDates.
However, based on your comments it seems orderDates refers to the day the order will ship. That date must be more than 2 days in the future for the user to cancel his order, so we're interested in orderDates - Today.
I don't see where you run the order date logic inside GridView1_RowDataBound.
Private Function MoreThanTwoDaysUntilShip() As Boolean
'logic to open dr1
If dr1.Read() Then
Dim shipDate As Date = DateTime.Parse(dr1("orderDates").ToString())
Dim today As Date = Date.Now
Return shipDate.Subtract(today).TotalDays > 2
End If
Return False
End Function
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
' Create cancel training button
Dim cancelBtn As New Button()
cancelBtn.Style.Add("width", "105px")
cancelBtn.Style.Add("padding", "5px")
cancelBtn.Style.Add("margin", "5px")
'add this
cancelBtn.Enabled = MoreThanTwoDaysUntilShip()
'etc
End Sub
DateTime.Parse(Now().ToString()).ToShortDateString()
Replace with
Today
And otherwise, don't manipulate dates in strings.

Error Cannot have multiple items selected in a DropDownList

This is my code and i am getting an error ..Cannot have multiple items selected in a DropDownList. when the page loads it select "ALL" in DDLModality but when i change DDLModality.selectedvalue to any "value" then no error but again when i change to "ALL "getting the error.
onchange of DDLMODALITY submit the form
form1.target = "";
form1.action = "";
form1.submit();
' USED TO ADD REFERRING PHYSICIAN IN THE DROPDOWN DYNAMICALLY
If CInt(Session("CenterID")) = 0 Then
sql = "Select Ref_Phy_ID,Name from Ref_Phy_Master WHERE Ref_Phy_ID in(Select distinct Ref_Phy_ID from Patient_Details where Ref_Phy_ID <> '')"
Else
sql = "Select Ref_Phy_ID,Name from Ref_Phy_Master WHERE Ref_Phy_ID in(Select distinct Ref_Phy_ID from Patient_Details where Ref_Phy_ID <> '') And Center_ID = " & Session("CenterID")
End If
objDS = objFun.RunQuery(sql)
' USED TO REFRESH THE PAGE WHIN IT IS POSTED BACK
' USED TO DISPLAY DEFAULT FIRST ITEM IN THE DROPDOWN
Dim Li1 As New ListItem()
Li1.Text = "ALL"
Li1.Value = ""
cboRefPhy.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)("Name").ToString()
Li.Value = objDS.Tables(0).Rows(i)("Ref_Phy_ID").ToString()
'USED TO ADD ITEMS IN THE DROPDOWN
cboRefPhy.Items.Add(Li)
Next
End If
'USED TO SAVE THE CHANGES IN DATASET
objDS.AcceptChanges()
' USED TO CLOSE THE DATABASE CONNECTION
objDS.Dispose()
cboRefPhy.ClearSelection()
cboRefPhy.SelectedValue = Convert.ToString(Request.Form("cboRefPhy"))
'USED TO ADD MODALITY IN THE DROPDOWN DYNAMICALLY
If CInt(Session("CenterID")) = 0 Then
sqlStudy = "Select Modality_ID,Modality from Hospital_Modality_Master WHERE Modality_ID in(Select distinct Study_ID from Patient_Details where Study_ID <> '')"
Else
sqlStudy = "Select Modality_ID,Modality from Hospital_Modality_Master WHERE Modality_ID in(Select distinct Study_ID from Patient_Details where Study_ID <> '') And Center_ID = " & Session("CenterID")
End If
'Dim objDS As New DataSet()
objDS = objFun.RunQuery(sqlStudy)
' USED TO REFRESH THE PAGE WHIN IT IS POSTED BACK
' USED TO DISPLAY DEFAULT FIRST ITEM IN THE DROPDOWN
'Dim Li1 As New ListItem()
Li1.Text = "ALL"
Li1.Value = ""
' Dim all As String
' all = "All"
'Ddl_Modality.Items.Add(all)
DDLModality.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)("Modality").ToString()
Li.Value = objDS.Tables(0).Rows(i)("Modality_ID").ToString()
'USED TO ADD ITEMS IN THE DROPDOWN
DDLModality.Items.Add(Li)
Next
End If
'USED TO SAVE THE CHANGES IN DATASET
objDS.AcceptChanges()
' USED TO CLOSE THE DATABASE CONNECTION
objDS.Dispose()
DDLModality.ClearSelection()
DDLModality.SelectedValue = Convert.ToString(Request.Form("DDLModality"))
' USED TO ADD STUDY IN THE DROPDOWN DYNAMICALLY
If CInt(Session("CenterID")) = 0 Then
sqlStudy = "Select Study_ID,Study_Desc from Study_Master WHERE Study_ID in(Select distinct Study_ID from Patient_Details where Study_ID <> '')"
Else
sqlStudy = "Select Study_ID,Study_Desc from Study_Master WHERE Study_ID in(Select distinct Study_ID from Patient_Details where Study_ID <> '') And Center_ID = " & Session("CenterID")
End If
If (DDLModality.SelectedItem.Text <> "ALL") Then
sqlStudy = sqlStudy & " AND Modality = '" & DDLModality.SelectedItem.Text & "'"
End If
try
DDLModality.ClearSelection()
before setting DDLModality.SelectedValue
Dim Li2 As New ListItem()
Li2.Text = "ALL"
Li2.Value = ""
DDLModality.Items.Add(Li2)
I was facing the same problem. If you add one defined ListItem (in this case Li1) to two or more dropdownlists, this error will occur while assigning selectedvalue to any dropdownlist.
Simple solution is define separate ListItems for separate dropdownlists like Li1, Li2, Li3, etc.
Don't understand the logic behind, but it works!

Resources