Error Cannot have multiple items selected in a DropDownList - asp.net

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!

Related

Dynamically Create Controls Based On Database field Asp.net

I have a database table that looks like so:
fieldid
form_id
control_type
parentid
order_number
1
1
panel
0
0
2
1
textbox
0
1
3
1
checkbox
0
0
4
1
panel
1
0
1
1
checkbox
4
0
1
1
textbox
4
1
There are other fields that I want to attach to this table but I want to dynamically create controls within the associated panel by using recursion.
I call the load_form with two parameters from the page_load event
my page has one panel in it called PnlMain and this panel is where I want the dynamically loaded controls placed within.
can anyone help me out with how to load only the controls that are associated with the "panels" with the fieldid that's equal to the associated controls parentid
Here is my code behind.
Sub load_form(c As Control, Optional parent_id As Integer = 0)
i = i + 1
Dim frmid As Integer
If Request("formid") Is Nothing Then
frmid = 1
Else
frmid = Request("formid")
End If
Dim dt As DataTable
Dim sql As String = ""
If parent_id = 0 Then
sql = "SELECT * from form_fields where form_id=" & frmid & " order by parentid, order_number"
dt = GetData(sql)
Else
sql = "SELECT * from form_fields where form_id=" & frmid & " and parentid=" & parent_id & " order by parentid, order_number"
dt = GetData(sql)
End If
If dt.Rows.Count > 0 Then
For Each row As DataRow In dt.Rows
' MsgBox(sql)
Dim p As New Panel()
If row(2).ToString.Trim(" ") = "panel" Then
' MsgBox(dt.Rows(0)(0))
Dim pnl As New Panel()
pnl.ID = "pnl" & row(0)
pnl.GroupingText = row(9)
p = pnl
load_form(p, row(0))
End If
If row(2).ToString.Trim() = "textbox" Then
Dim t As New TextBox With {
.CssClass = "form-control"}
t.Attributes.Add("showto", "true")
t.Attributes.Add("dbdata", "true")
t.Attributes.Add("placeholder", "Enter O2 Level...")
t.ID = "Txt" & i
p.Controls.Add(t)
End If
If row(2).ToString.Trim() = "checkbox" Then
Dim cb As New CheckBox With {
.CssClass = "cb form-control"}
cb.Attributes.Add("showto", "All")
cb.Attributes.Add("dbdata", "true")
cb.Attributes.Add("title", row("title").ToString.Trim())
cb.Attributes.Add("altValue", row("altvalue").ToString.Trim())
cb.Text = row(7).ToString.Trim()
cb.ID = "cb" & i
p.Controls.Add(cb)
End If
c.Controls.Add(p)
Next
End If
End Sub

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!

Database query result to display in Label VB.net

I have a label in which I want to display my database query result. But the label displaying only first row not all the records. Can anyone here could help me with this? Tried searching but I found other answers confusing. Please help me.
Here is what I have so far.
FrontEnd
<asp:Label ID="Resulttext" runat="server" Text=""></asp:Label>
Backend
Protected Sub getUser()
Dim dt As New DataTable()
Dim conn As SqlConnection = New SqlConnection("myconnectionhere")
conn.Open()
Dim cmd As SqlCommand = New SqlCommand("mysqlhere", conn)
Dim da As SqlDataAdapter = New SqlDataAdapter(cmd)
da.SelectCommand = cmd
da.Fill(dt)
If dt.Rows.Count > 0 Then
Resulttext.Text = dt.Rows(0)("Fullname").ToString
End If
conn.Close()
End Sub
What I'm doing wrong? Thank you.
Already solve the problem and here is the answer.
If dt.Rows.Count > 0 Then
For i As Integer = 0 To dt.Rows.Count - 1
Resulttext.Text = dt.Rows(i)("Fullname").ToString & " " & Resulttext.Text
Next
End If
Resulttext.Text = dt.Rows(0)("Fullname").ToString
You are writing above code for display record in the Lable.
Meaning of above code is dt.Rows(RowIndex)(ColumnIndex/"Column valuse")
You passed 0 in the RowIndex Means it gives you First row and passed "FullName" in column value , So it gives fullname value of First row.
That's why it displays only one record.
For display all the value of FullName you have to change your query as below.
select distinct t1.id,
STUFF(
(SELECT ', ' + FullName
FROM yourtable t2
where t1.id = t2.id
FOR XML PATH (''))
, 1, 1, '') AS fullname
from yourtable t1;
Thus it gives fullName as comma separated and then you can write code
Resulttext.Text = dt.Rows(0)("Fullname").ToString
And it gives CSV for fullname and displays in the label

Index was out of range. Must be non-negative and less than the size of the collection - chart databind

I'm trying to build a datatable and then bind it to a gridview and chart object. The gridview appears fine but when I build the x,y array and bind them to the chart object I get the error above.
I've read many forums to understand that the index is looking at a field that is out of range but I've queried in the immediate window all the fields and the are clearly values there. There error occurs as soon as I bind it to the chart object and I don't know why the chart object doesn't just display properly.
This is my aspx codebehind:
Dim dt As DataTable = New DataTable()
dt.Columns.Add("CompanyName")
dt.Columns.Add("Amount")
dt.Columns.Add("Proportion")
Using DBContext As New fundmatrixEntities
Dim queryUnits = (From c In DBContext.Units Where c.SavingApplicationId = savAppId Select New With {.LoanAppId = c.LoanApplicationId}).Distinct().ToList()
Dim companyName As String = ""
Dim savingsAmount As String = ""
Dim totalProportion As String = ""
Dim totalSavingsAmount As String = ""
For Each loan In queryUnits
If Not loan.LoanAppId Is Nothing Then
companyName = classSQLDirect.ExecQuery("SELECT companyname FROM companyprofile where loanapplicationid='" & loan.LoanAppId.ToString & "'")
savingsAmount = classSQLDirect.ExecQuery("SELECT SUM(Amount) from unit where SavingApplicationId='" & savAppId.ToString & "' and LoanApplicationId='" & loan.LoanAppId.ToString & "'")
totalSavingsAmount = classSQLDirect.ExecQuery("SELECT amount FROM SavingApplication WHERE SavingApplicationId='" & savAppId.ToString & "'")
totalProportion = ((savingsAmount / totalSavingsAmount) * 100) & "%"
dt.Rows.Add(companyName, savingsAmount, totalProportion)
End If
Next
gvwBusinesses.DataSource = dt
gvwBusinesses.DataBind()
End Using
Dim x As String() = New String(dt.Rows.Count - 1) {}
Dim y As String() = New String(dt.Rows.Count - 1) {}
For i As Integer = 0 To dt.Rows.Count - 1
x(i) = dt.Rows(i)(0).ToString()
y(i) = dt.Rows(i)(2).ToString()
Next
chart1.Series(0).Points.DataBindXY(x, y)
chart1.Series(0).ChartType = SeriesChartType.Pie
The code errors on the line
chart1.Series(0).Points.DataBindXY(x, y)

Copy records to another recordset using Active Server Page

I'm programming in Classic ASP. I'm trying to do the paging. My backend is SQL CE 3.5. Unfortunetly, it doesn't support paging in SQL Query (Like row_number() in sql server).
So I go with ASP Paging. But when i ask to the recordset, give me the first 10 records by setting the rs.PageSize and rs.AbsolutePage and all, it gives me all records. So I planned to copy only first 10 rows from the resultant recordset to another new recordset. So I coded like below:
Set rsTemp = CopyRecordsetStructure(objRs)
rsTemp.Open
iRecordsShown = 0
Set objFields = objRs.Fields
intFieldsCount = objFields.Count-1
Do While iRecordsShown < intPageSize And Not objRs.EOF
rsTemp.AddNew
For Idx = 0 To intFieldsCount
rsTemp.Fields(Idx).Value = objRs.Fields(Idx).Value
Next
rsTemp.Update
iRecordsShown = iRecordsShown + 1
objRs.MoveNext
Loop
Public Function CopyRecordsetStructure(ByVal rs)
Dim rsTemp
Set rsTemp = CreateObject("ADODB.Recordset")
Set objFields = rsTemp.Fields
intFieldCount = objFields.Count - 1
For Idx = 0 To intFieldCount
rsTemp.Fields.Append objFields(Idx).Name, _
objFields(Idx).Type, _
objFields(Idx).DefinedSize
Next
Set CopyRecordsetStructure = rsTemp
End Function
The issue is i could not open the" rsTemp". It throws me error
The connection cannot be used to perform this operation. It is either closed or invalid in this context.
If I use some dummy query and connection it doesn't work.
Please help to copy the records from one recordset to another new record set.
Thanks in advance
Ganesh.
Not sure, but this looks wrong
Set objFields = rsTemp.Fields
Shouldn't it be
Set objFields = rs.Fields
With the comments and fixed in the above comments, the function should be updated Set objFields = rs.Fields to:
Usage:
Dim rsTemp
Set rsTemp = CopyRecordset(rsPadicon)
Update Code
Public Function CopyRecordset(rs)
Dim rsTemp, objFields, intFieldsCount, intPageSize
Set rsTemp = CopyRecordsetStructure(rs)
rsTemp.Open
Set objFields = rs.Fields
intFieldsCount = objFields.Count-1
response.write("<li> rs.RecordCount :" & rs.RecordCount & "</li>")
' response.write("<li> intFieldsCount :" & intFieldsCount & "</li>")
rs.MoveFirst
Do While Not rs.EOF
rsTemp.AddNew
Dim i
For i = 0 to intFieldsCount 'use i as a counter
' response.write("<li> Name :" & rs.Fields(i).Name & "</li>")
' response.write("<li> Value :" & rs.Fields(i).Value & "</li>")
if Not IsNull(rs.Fields(i).Value) then
rsTemp.Fields(i).Value = rs.Fields(i).Value
End if
Next
rsTemp.Update
rs.MoveNext
Loop
Set CopyRecordset = rsTemp
End Function
Public Function CopyRecordsetStructure(ByVal rs)
Dim rsTemp, objFields, intFieldCount, Idx
Set rsTemp = CreateObject("ADODB.Recordset")
Set objFields = rs.Fields
intFieldCount = objFields.Count - 1
For Idx = 0 To intFieldCount
rsTemp.Fields.Append objFields(Idx).Name, _
objFields(Idx).Type, _
objFields(Idx).DefinedSize
Next
Set CopyRecordsetStructure = rsTemp
End Function

Resources