I want datareader to read data from a column in database which is varchar and the read result to be stored in string variable - sqldatareader

I want datareader to read data from a column in database which is varchar and the read result to be stored in string variable but it generates an indexoutofrange exception...Basically I want a validation so that if the user enters a booking time which is already in the database then program should generate an error message. Also an error should be generated if entered value is inside the booked time duration. Like if a booking is there on 12/12/2011 at 4:00 pm and the duration is 2 hours then the program should not allow any booking till 6:00 pm unless a booking is for some other game or for some other courtno (in case of badminton, squash, lawn tennis etc)
I'm trying the following code for this:
Dim str2 As String ' defines string variable for taking select query
str2 = "select booking_date, booking_time, booking_duration, poolno, courtno, tableno from Bookings"
Dim a, b As Date
Dim c As Date
Dim d, f, g, l As String
Dim dur As Integer
Dim cmd2 As New SqlCommand(str2, con)
con.Open()
Dim bookchk As SqlDataReader = cmd2.ExecuteReader
While bookchk.Read()
a = bookchk("booking_date")
b = bookchk("booking_time")
c = b.ToLongTimeString
dur = bookchk("booking_duration")
l = bookchk("game") 'exception is generated here
If CmboGame.SelectedItem = "Swimming" Then
If bookchk("poolno") IsNot System.DBNull.Value Then
d = bookchk("poolno")
End If
Else : d = ""
End If
If CmboGame.SelectedItem = "Table Tennis" Then
If bookchk("tableno") IsNot System.DBNull.Value Then
f = bookchk("tableno")
End If
Else : f = ""
End If
If CmboGame.SelectedItem IsNot "Table Tennis" And CmboGame.SelectedItem IsNot "Swimming" Then
If bookchk("courtno") IsNot System.DBNull.Value Then
g = bookchk("courtno")
End If
Else : g = ""
End If
If TxtBookDate.Text = a And TxtBookTime.Text = c And TxtPoolNo.Text = d And TxtCrtNo.Text = g And TxtTblNo.Text = f And CmboGame.SelectedItem = l Then
MessageBox.Show("The date and time you have entered has already been booked" & vbCrLf & "Try Again!", "Bookings Overlapped", MessageBoxButtons.OK, MessageBoxIcon.Stop)
Exit Sub
End If
Dim time, h, i, j, n As DateTime
n = c.AddHours(dur)
time = TxtBookTime.Text
h = time.AddHours(TxtBookDur.Text)
i = time.ToLongTimeString
j = h.ToLongTimeString
If TxtBookDate.Text = a And TxtPoolNo.Text = d And TxtCrtNo.Text = g And TxtTblNo.Text = f And CmboGame.SelectedIndex = l And i > c And i <= n Or j > n Then
MessageBox.Show("The date and time you have entered has already been booked" & vbCrLf & "Try Again!", "Bookings Overlapped", MessageBoxButtons.OK, MessageBoxIcon.Stop)
Exit Sub
End If
End While
bookchk.Close()
con.Close()

Your SQL statement:
str2 = "select booking_date, booking_time, booking_duration, poolno, courtno, tableno from Bookings"
You're not selecting a column called "game", so obviously you can't reference this in your datareader. Add the "game" column to the SQL statement, assuming it exists, this problem will disappear. You might have other problems of course.

Related

ASP.NET vb oracle database Date input error

Im using following code to input data into orcale database via asp.net web application (vb).
Public Sub SaveRaidDetails()
lblStatus.Text = ""
Dim dt2 As DataTable = CType(ViewState("dt1"), DataTable)
Dim er As Boolean = False
Dim dtRaidDate As Date
If dt2.Rows.Count > 0 Then
Try
dtRaidDate = Convert.ToDateTime(txtRaidDate.Text)
Catch ex As Exception
er = True
End Try
If er = False Then
lblDateEr.Visible = False
Dim intDisID, intMktSeq, intAgID As Integer
Dim dblFine As Double
If ddlDistributor.SelectedValue = "" Then
intDisID = 0
Else
intDisID = ddlDistributor.SelectedValue
End If
If ddlMarkets.SelectedValue = "" Then
intMktSeq = 0
Else
intMktSeq = ddlMarkets.SelectedValue
End If
If ddlAgency.SelectedValue = "" Then
intAgID = 0
Else
intAgID = ddlAgency.SelectedValue
End If
If txtFine.Text = "" Then
dblFine = 0
Else
dblFine = Convert.ToDouble((txtFine.Text))
End If
Dim intUserSeq As Integer = Convert.ToInt32(Session("UserSeq"))
Dim ret As Boolean
Dim rd1 As New RIMS_DATA.Raids
ret = rd1.AddRaid(dtRaidDate, txtCo.Text, txtCa.Text, intDisID, Convert.ToInt32(ddlRegion.SelectedValue), intAgID, intMktSeq, txtTrader.Text, txtTraderAdd.Text, dblFine, txtRemarks.Text, intUserSeq)
If ret = True Then
Dim intRaidID As Integer = rd1.ReadLastRaid()
Dim dtBatchDt As Date
For Each dr As DataRow In dt2.Rows
Try
dtBatchDt = Convert.ToDateTime(dr("BDt"))
Catch ex As Exception
dtBatchDt = Convert.ToDateTime("01/01/2000")
End Try
ret = rd1.AddRaid2(intRaidID, Convert.ToInt32(dr("BID")), Convert.ToInt32(dr("Qty")), dr("BCd"), dtBatchDt)
Next
ClearForm(1)
lblStatus.Text = "Record inserted successfully !"
lblDateEr.Visible = True
End If
End If
End If
Else
lblStatus.Text = "Please enter the raid details !"
End If
But the issue is in the Orcle database the date is saved in wrong format like this.. 20/07/0001 . But the date in the text box which i pass to variable is 2015/07/1. I use date time picker to input date to text box. how can i fix this problem.
Is this enough for answer

Validate that textbox has numeric value in vb.net and compare value with database

enter image description hereI'm trying to validate a textbox where users will put an ID. The ID has to be numeric and at the same time compare to a valid ID in the database. When I was just validating for numeric, I didn't have any problems. But now that I have two conditions, my code doesn't work properly. Whenever I type in letters in the textbox and click a button, it gives me an error. The boolean is throwing me off lol. Below is my code:
Thank you in advance.
Protected Sub btnGo_Click(sender As Object, e As EventArgs) Handles btnGo.Click
Dim dt As DataTable
Dim dr As DataRow
Dim Conn As New SqlConnection("Data Source=Computer;Initial Catalog=Catalog;Persist Security Info=True;User ID=userid;Password=password")
Dim cmd As New SqlCommand("SELECT COUNT(*) FROM [tbl] WHERE [ID]=#Value", Conn)
cmd.Parameters.Add("#Value", SqlDbType.NVarChar).Value = txtId.Text
Conn.Open()
Dim valueExistsInDB As Boolean = CBool(CInt(cmd.ExecuteScalar()) > 0)
Conn.Close()
If (IsNumeric(txtId.Text)) AndAlso valueExistsInDB = True AndAlso txtId.Text IsNot Nothing Then
dt = GetDataTable("SELECT ID, LEFT(SANZ_ID, PATINDEX('%.%', SANZ_ID) -1) AS City, CASE WHEN ST_DIR_ID = 1 THEN 'NB' WHEN ST_DIR_ID = 2 THEN 'SB' WHEN ST_DIR_ID = 3 THEN 'EB' WHEN ST_DIR_ID = 4 THEN 'WB' END AS ST_DIR, STREET_OF_TRAVEL, CROSS_STREET, (SELECT TOP 1 CASE WHEN STATUS_ID = 1 THEN 'F' WHEN STATUS_ID = 2 THEN 'P' WHEN STATUS_ID = 3 THEN 'I' WHEN STATUS_ID = 4 THEN 'N' WHEN STATUS_ID = 5 THEN 'A' END FROM tbl where dbo.tbl.ID=ID) AS STATUS FROM tbl WHERE ID=" & txtId.Text)
dr = dt.Rows(0)
labelStreet.Text = dr("street_of_travel")
labelCrossStreet.Text = dr("cross_street")
labelCity.Text = dr("city")
labelDir.Text = dr("st_dir")
labelAda.Text = dr("STATUS")
'dropdownStatus.SelectedValue=
dropdownStatus.Visible = True
txtNotes.Visible = True
btnSave.Visible = True
Else
MessageBox.Show("ID not found! Please input a valid ID.")
End If
End Sub
If ID is a numeric field then you should pass a numeric parameter not an NVarChar one
' First try to convert the input text to an integer '
' this should be done here before acting on the db '
Dim id As Integer
if Not Int32.TryParse(txtId.Text, id) Then
MessageBox.Show("Error, not a valid number")
return
End If
Dim cmdText = "SELECT COUNT(*) FROM [tbl] WHERE [ID]=#Value"
Using Conn = New SqlConnection(....)
Using cmd As New SqlCommand(cmdText, Conn)
cmd.Parameters.Add("#Value", SqlDbType.Int).Value = id
Conn.Open()
Dim valueExistsInDB = CBool(CInt(cmd.ExecuteScalar()) > 0)
' At this point you don't need anymore to check if the input value'
' is numeric and your if is more simple.....'
if valueExistsInDB Then
......
... continue with your code ....
Else
MessageBox.Show("ID not found! Please input a valid ID.")
End if
End Using
End Using

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)

Creating SQL query in VB.net from a Checkboxlist

I have a checkboxlist and I populate it dynamically from a database. For example after i populate the checkboxlist is like that:
Los Angeles
New York
London
Berlin
Amsterdam
I want to create a SQL query according to the checkboxes are checked. If i want to choose only one city (e.g. only New York) i want the result to be:
(City = 2)
Thats works properly but when i have multiple cities (e.g. New York, London and Amsterdam) i want the result to be for example:
(City = 2) OR (City = 3) OR (City = 5)
Or if i choose Los Angeles and Berlin I want the result to be like this:
(City = 1) OR (City = 4)
How can i achieve this? That's my code below but I am stacked. Any ideas?
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim var As String = ""
Dim counter As Integer = 0
Dim myList As New List(Of String)()
For i As Integer = 0 To CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
myList.Add(i + 1)
counter = counter + 1
If counter = 1 Then
var = "(City =" & i + 1 & ")"
Else
Console.WriteLine(myList(1))
Dim myArray As String() = myList.ToArray()
For j As Integer = 1 To myArray.Length
Dim var2 As String = " OR (City =" & counter & ")"
var = "(City =" & myArray(0) & ")" & var2
Next
End If
End If
Next
SQL = "SELECT * FROM Data1 WHERE (" & var & ") ORDER BY [ID]"
Session("Search") = SQL
Server.Transfer("Data_Form.aspx")
End Sub
What I recommend most strongly is to look into Table-value Parameters:
http://msdn.microsoft.com/en-us/library/bb675163(v=vs.110).aspx
This will fix your issue and help you avoid sql injection vulnerabilities.
But if you really insist on using string concatenation, try using an IN() condition, where you end up with something more like CITY IN (1,2) instead of (City = 1 OR City = 2). You can make this a bit easier to write by leading with an unused ID, like so:
Dim cityClause As String = " CITY IN (-1{0})" 'start with a valid clause
Dim cityIDs As String = ""
For Each box As ListItem In CheckBoxList1.Items.Where(Function(b) b.Selected)
'Try storing the ID for each city in the value part of each listitem,
' rather than using the index order
cityIDs = cityIDs & "," & box.Value
Next box
cityClause = string.Format(cityClause, cityIDs)
You can use City IN(2,3,5) instead of (City = 2) OR (City = 3) OR (City = 5):
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim condition As String = ""
For i As Integer = 0 To CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
condition = condition & "," & (i + 1)
End If
Next
SQL = "SELECT * FROM Data1 WHERE (" & condition.SubString(1) & ") ORDER BY [ID]"
Session("Search") = SQL
Server.Transfer("Data_Form.aspx")
End Sub

Array list error second array replace the first array

I have a problem.
Dim Maxis As String
'Dim MaxisExtra As String
Dim b As New ArrayList
Dim WS As New WebService1.Service1
Dim cnt As String
Dim MRWS As New MobileReload_WS.MobileReload_WS
cnt = WS.StockCountTelco(1, Session("Maxis"))
If CInt(cnt) >= CInt(DropDownList1.SelectedItem.Text) Then
Dim sLock As String
sLock = MRWS.LockAStock(1, 1, "Online", Session("Maxis"), DropDownList1.SelectedItem.Text)
Session("sLock") = sLock
If sLock = "" Then
PopupMsgBox("Unable to allocate Stock")
Else
Maxis = "Maxis" & ";" & Session("Maxis") & ";" & DropDownList1.SelectedItem.Text & ";" & Session("Cost")
'If MaxisExtra = "" Then
' b.Add(Maxis)
' Elseif
' MaxisExtra = MaxisExtra + Maxis
' b.Add(MaxisExtra)
'End If
End If
Else
PopupMsgBox("Not enough stock")
End If
b.Add(Maxis)
Session("Transaction") = b
End Sub
The first time i enter the string into the arraylist it is okay. But when the user press the button add again the second time, it replace the first string. Can anyone help me how to save the string into the second slot based on my coding?
If you're talking about the b ArrayList, then you're creating a new one each time and storing the new ArrayList in Session("Transaction")
Maybe you mean something like this instead...
Dim b as ArrayList = Session("Transaction")
If b Is Nothing Then
b = new ArrayList
End If
...
Session("Transaction") = b
Although it's difficult to say exactly, because your code is very messy and not clear
You put the array list in a session variable, but you never read it back. You create a new array list each time, so it will always be empty and replace the previous one.
Get the array list from the session variable if there is one:
Dim b As ArrayList = Session("Transaction")
If b Is Nothing Then b = New ArrayList

Resources