UPDATE>>>> If I run this on localhost, their is no duplication of data, but on the site there is. Does that help to give people an idea of what may be going on?
I have an application built by someone else that is returning results from a socket call when the end user types in a little product info, and hits submit. The application returns the results, but it sometimes displays the results twice. For example, if I click submit on the application to do a search for a product, it may come back with the correct one, two, or three records (as there could be results from 1-3 locations), or it may repeat all those results twice. (Ie.: if there were two records returned, it might simply display the info from the two records, or it may display the results from the two records in the first two rows of the , and then repeat rows 1 & 2 in rows 3 & 4.) Continuing to click submit on that page will (it appears randomly) change the resulting displayed data - cycling between one set of results and two.
Any ideas on what may be causing this? I've included the bit of code I think is involved. I inherited this code, and am trying to make it work, but I'm new to this type of application and only intermediate at best in asp.net. Thank-you in advance to anyone who can shed some light!!
Protected Sub displayTableOne(ByVal records() As String)
Dim dt As New DataTable()
Dim values() As String = {""}
Dim i As Integer = 0
Try
Dim Row() As String = {"Company", "Piece", "Description", _
"Location", "Available", "Purchased", "Ship Date"}
#Create the columns
Dim column1 As New DataColumn("Company", GetType(String))
Dim column2 As New DataColumn("Piece", GetType(String))
Dim column3 As New DataColumn("Description", GetType(String))
Dim column4 As New DataColumn("Location", GetType(String))
Dim column5 As New DataColumn("Available", GetType(String))
Dim column6 As New DataColumn("Purchased", GetType(String))
Dim column7 As New DataColumn("Ship Date", GetType(String))
dt.Columns.Add(column1)
dt.Columns.Add(column2)
dt.Columns.Add(column3)
dt.Columns.Add(column4)
dt.Columns.Add(column5)
dt.Columns.Add(column6)
dt.Columns.Add(column7)
If (records.Length > 1) Then
For i = 0 To records.Length - 2 Step 1
values = Split(records(i), "|")
Dim l As Integer = 0
Dim dr As DataRow
dr = dt.NewRow()
If values(0) = "05" Then
If (values.Length > 4) Then
dr(Row(0)) = values(1)
dr(Row(1)) = values(2)
dr(Row(2)) = values(13)
dr(Row(3)) = values(17)
dr(Row(4)) = values(7)
dr(Row(5)) = values(15)
dr(Row(6)) = values(16)
End If
dt.Rows.Add(dr)
End If
Next
If values(23) = "Error" Then
invalidMessage()
Else
#Bind the DataTable to the DataGrid
Table1.Visible = True
Table1.DataSource = dt
Table1.DataBind()
End If
End If
Catch ex As Exception
invalidMessage()
Finally
Array.Clear(records, 0, records.Length)
Array.Clear(values, 0, values.Length)
End Try
End Sub
Related
I am dynamically creating checkboxes in VB.Net and an .aspx page, based on values in my db. I'm placing them in a two column table for ease of alignment. this part works fine.
Private Async Function InitForEditAsync() As Task
Dim docList = Await GetLoanApplicationConfigurationDocs()
Dim row = New HtmlTableRow()
Dim cell = New HtmlTableCell()
Dim i = 0
For Each doc In docList
Dim chkBox = New HtmlInputCheckBox()
Dim lbl = New Label()
Dim remainder = i Mod 2
chkBox.ID = "chkDocId" + doc.Id.ToString
lbl.Text = doc.DisplayName
cell.Controls.Add(chkBox)
cell.Controls.Add(lbl)
row.Cells.Add(cell)
cell = New HtmlTableCell()
If remainder <> 0 OrElse i = docList.Count() - 1 Then
tblEdit.Rows.Add(row)
row = New HtmlTableRow()
End If
i += 1
Next
End Function
Now I need to retrieve the values without knowing the id's but am not having any luck. I tried this:
For Each chkBox As HtmlInputCheckBox In pnlEdit.Controls.OfType(Of HtmlInputCheckBox)
but the checkboxes are not returned in the list of controls. The table is, but there are no rows in the table object when I explored it in the control collection and when I tried this:
For Each row As HtmlTableRow In tblEdit.Rows.OfType(Of HtmlTableRow)
If it will help, here is a Snip of the UI and the HTML that is created:
Any suggestions are appreciated. Thanks in advance.
Based on some ideas I got from another site, I'm going to rewrite this using the asp:CheckBoxList. apparently it binds like a datagrid and you can enumerate through it. Seems like what i need.
UPDATE: Everything I posted to start was resolved with five lines of code! "cblDocList is my asp CheckboxList and docList is my ienumerable of objects.
cblDocList.RepeatColumns = 2
cblDocList.DataSource = docList
cblDocList.DataTextField = "DisplayName"
cblDocList.DataValueField = "Id"
cblDocList.DataBind()
It’s something you can do through a loop for each row and each cell or using Linq to have only cells that have controls of type HtmlInputCheckBox inside.
I have simplified your code to be able run that here also shows you an example to achieve your task. Obviously you must change following your exigences .
Hope I well understood :)
Dim tblEdit As New HtmlTable
For k As Integer = 0 To 10
Dim cell = New HtmlTableCell()
Dim row = New HtmlTableRow()
Dim chkBox = New HtmlInputCheckBox()
Dim lbl = New Label()
Dim remainder = k Mod 2
chkBox.ID = "chkDocId_" + k.ToString
chkBox.Checked = remainder = 0
lbl.Text = "Text indicator of CheckBox nr:" + k.ToString
cell.Controls.Add(chkBox)
cell.Controls.Add(lbl)
row.Cells.Add(cell)
cell = New HtmlTableCell()
tblEdit.Rows.Add(row)
Next
Dim checkBoxes As IEnumerable(Of HtmlInputCheckBox) =
(From mRow In tblEdit.Rows).Select(Function(mr)
Dim cb = (From cc In CType(mr, HtmlTableRow).Cells
Where CType(cc, HtmlTableCell).Controls.OfType(Of HtmlInputCheckBox).Count > 0
Select CType(cc, HtmlTableCell).Controls.OfType(Of HtmlInputCheckBox)()(0)).FirstOrDefault
Return CType(cb, HtmlInputCheckBox)
End Function).ToList
For Each checkBox In checkBoxes
Debug.WriteLine("CheckBox ID: {0} Checked: {1} ", checkBox.ID, checkBox.Checked)
Next
I have a reservation page and a reservation table which contains reservationstart column, reservationend column and numofdays column.
I have determined the number of days between the two dates which a client will select but nothing was stored in the table when I update.
The data type of numofdays was datatime but I have changed this to int.
I used this first, to declare the start and end date:
DayPilotScheduler1.Scale = TimeScale.Manual
Dim start As New Date(Date.Today.Year, 1, 1, 12, 0, 0)
Dim [end] As Date = start.AddYears(1)
This is the code for the update:
Protected Sub DayPilotScheduler1_EventMove(ByVal sender As Object, ByVal e As DayPilot.Web.Ui.Events.EventMoveEventArgs)
Dim id_Renamed As String = e.Value
Dim start As Date = e.NewStart
Dim [end] As Date = e.NewEnd
Dim resource As String = e.NewResource
Dim message As String = Nothing
If Not dbIsFree(id_Renamed, start, [end], resource) Then
message = "The reservation cannot overlap with an existing reservation."
ElseIf e.OldEnd <= Date.Today Then
message = "This reservation cannot be changed anymore."
ElseIf e.OldStart < Date.Today Then
If e.OldResource <> e.NewResource Then
message = "The room cannot be changed anymore."
Else
message = "The reservation start cannot be changed anymore."
End If
ElseIf e.NewStart < Date.Today Then
message = "The reservation cannot be moved to the past."
Else
dbUpdateEvent(id_Renamed, start, [end], resource)
'message = "Reservation moved.";
End If
LoadResourcesAndEvents()
DayPilotScheduler1.UpdateWithMessage(message)
End Sub
Private Sub dbUpdateEvent(ByVal id As String, ByVal start As Date, ByVal [end] As Date, ByVal resource As String)
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("connectionStringLocal").ConnectionString)
con.Open()
Dim numOfDay As Integer = CInt(([end] - start).TotalDays())
Dim cmd As New SqlCommand("UPDATE [Reservation] SET ReservationStart = #start, ReservationEnd = #end, RoomId = #resource,numofday=#numofday WHERE ReservationId = #id", con)
cmd.Parameters.AddWithValue("id", id)
cmd.Parameters.AddWithValue("start", start)
cmd.Parameters.AddWithValue("end", [end])
cmd.Parameters.AddWithValue("resource", resource)
cmd.Parameters.Add("numofday", SqlDbType.Int).Value = numOfDay
cmd.ExecuteNonQuery()
End Using
End Sub
Screenshot of database table structure:
Math.floor(Math.abs(new Date(timestringone) - new Date(timestringtwo))/(1000*60*60*24))
Simply subtracting the dates returns the time in Milliseconds inbetween them. If the first time was before the second time the value is negative, so i used Math.abs to make it absolute. Then we divide trough 1000Milliseconds=1second, 60seconds=1minute, 60minutes=1hour, 24hours=1 day, and floor it to whole days. Requires two valid timestrings (timestringone and timestringtwo) to be given.
This is a javascript solution as youve included the js tag...
I am not sure about the VB.Net but you can easily accomplished it in C# using an object of Type "TimeSpan". For example: let's assume that we want to know the number of days between the start and end. values for the DateTime Type and show it in a Console window, then I may write something like:
DateTime start=DateTime.MinValue;
DateTime end=DateTime.MaxValue;
TimeSpan span=end-start;
Console.WriteLine( "There're {0} days between {1} and {2}" , span.TotalDays, start.ToString(), end.ToString() );
OP is having problems using the .Days property on the TimeSpan structure. I think this may help:
Dim numOfDay As Integer = CInt(([end] - start).TotalDays())
The output is:
365
Moving onto the use of your parameters, I think you would benefit from using .Add and specifying the data type:
cmd.Parameters.Add("#id", SqlDbType.Int).Value = id
cmd.Parameters.Add("#start", SqlDbType.Date).Value = start
cmd.Parameters.Add("#end", SqlDbType.Date).Value = [end]
cmd.Parameters.Add("#resource", SqlDbType.Int).Value = CInt(resource)
cmd.Parameters.Add("#numofday", SqlDbType.Int).Value = numOfDay
Note that you may have to change the SqlDbType. I've taken an assumption.
I would also implement Using for both the SqlConnection and SqlCommand. This for me is just good practice and the code does read better. I would also use the .Add overload for all parameters.
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("connectionStringLocal").ConnectionString),
cmd As New SqlCommand("UPDATE [Reservation] SET ReservationStart = #start, ReservationEnd = #end, RoomId = #resource, numofday = #numofday WHERE ReservationId = #id", con)
con.Open()
cmd.Parameters.Add("#id", SqlDbType.Int).Value = id
cmd.Parameters.Add("#start", SqlDbType.Date).Value = start
cmd.Parameters.Add("#end", SqlDbType.Date).Value = [end]
cmd.Parameters.Add("#resource", SqlDbType.Int).Value = CInt(resource)
cmd.Parameters.Add("#numofday", SqlDbType.Int).Value = CInt(([end] - start).TotalDays())
Dim rowsAffected As Integer = cmd.ExecuteNonQuery()
If rowsAffected = 0 Then
'nothing updated
Else
'something updated
End If
End Using
I have 2 comboboxes, cmbstud and cmbhostel. They are filled from the database by binding the datasource to the datatable. As I update, the cmbstud updates accordingly. When I update the last record the datatable empties, but cmbstud still retains the value. Cmbhostel data is bound to change index of cmbstud.
In the form load event I have this code:
Dim cmd As New SqlCommand("SELECT stud_id,name FROM student_details WHERE stud_id NOT IN (SELECT stud_id FROM student_details WHERE hostel_id!=0)", sqlcont.Conn)
Dim dr As SqlDataReader = cmd.ExecuteReader
Dim dat As New DataTable
Dim j As Integer
For j = 0 To dat.Rows.Count - 1
dr.Read()
Next
dat.Load(dr)
cmbstud.DisplayMember = "name"
cmbstud.ValueMember = "stud_id"
cmbstud.DataSource = New BindingSource(dat, Nothing)
dr.Close()
sqlcont.Conn.Close()
In my btnhostel for updating I have the following queries implemented and the following code to reload the form to refresh my datasources:
"UPDATE hostel SET in_use=in_use+1 WHERE hostel_id=#hostid"
"UPDATE student_details SET hostel_id=#hostid where stud_id=#stud_id"
frmallocateHostel_Load(Nothing, Nothing)
Cmbstud index change evnt code:
Dim sqcm5 As New SqlCommand("Select hostel.hostel_id,hostel.hostel_name From hostel Inner Join student_details On student_details.gender = hostel.hostel_gender where student_details.stud_id =" & cmbstud.SelectedValue.ToString & " ", sqlcont.Conn)
Dim datreadr5 As SqlDataReader = sqcm5.ExecuteReader
Dim dt5 As New DataTable
Dim n As Integer
For n = 0 To dt5.Rows.Count - 1
datreadr5.Read()
Next
dt5.Load(datreadr5)
cmbhostel.ValueMember = "hostel_id"
'asign value & display member b4 datasource to avoid errors
cmbhostel.DisplayMember = "hostel_name"
cmbhostel.DataSource = dt5
There are some similar questions: ComboBox has its old value after Clear(); however, they don't address my issue.
changing this did the trick:
Dim b As New BindingSource()
b.DataSource = dat
cmbstud.DataSource = b
b.ResetBindings(False)
i have this database table called people
People
peopleID peopleName relationship customerID
1 A aunty 1
2 B aunty 1
3 C second uncle 1
4 D aunty 2
how am i going to count the number of people where the customerID = 1 and if the relationship is the same, it is counted as 1
so from the database table above, i should get the result of 3 and put the result of 3 in Label1 in gridview?
i can get the count value for the only where the customerID =1 but i can't figure out how am i going to count if the relationship part
Protected Sub GridView2_RowDataBound(sender As Object, e As
System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView2.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
'Do your processing here...
Dim txt As TextBox = DirectCast(e.Row.FindControl("Label1"), TextBox)
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
'Dim sql As String
Dim connectionString = ConfigurationManager.ConnectionStrings("ProjData").ConnectionString
Dim myConn As New SqlConnection(connectionString)
Dim cmd = "Select * From People Where customerID='" & Session("customerID") & "' "
' Dim myCmd As New SqlCommand(cmd, myConn)
Try
myConn.Open()
Dim myCmd As New SqlCommand(cmd, myConn)
adapter.SelectCommand = myCmd
adapter.Fill(ds, "People")
adapter.Dispose()
myCmd.Dispose()
txt.Text = ds.Tables(0).Rows.Count
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End If
End Sub
You should wrap your SqlConnection in a using statement (not sure how you do that in VB). In your example you don't close the connection, the using statement does this for you automatically (the alternative is to close the connection in a finally block)
When i correctly understand your question, the following SQL Statement should give you the count as you need it.
Select count(peopleID)
From People
Where customerID = 1
Group by relationship, customerID
If this answer didn't solve your problem please add further information to your question.
In your code, you fetch all the rows and then count them. You can also execute a query that will count the number of rows on the server. This will perform much better!
string sql = "SELECT COUNT(*) FROM People Where customerID='" & Session("customerID") & "' "
...
int rowCount = myCmd.ExecuteScalar();
If you want to count the number of rows with the same relationship, you have to use a group by.
You have to change your sql to:
string sql = 'SELECT COUNT(peopleId) FROM People Where customerID='" & Session("customerID") & "' "GROUP BY relationship, customerId"
I have searched high and low to no avail, and this is last step before completing my project so please help! Thanks in advance!
The user will select an entry in a gridview, which then redirects them to a form that is populated with the data from the selected row (thus making the gridview editable in a more user friendly way). Null values are accepted by the DB and I would like to show null date values as blank (or " ") in the corresponding text boxes. Instead I get the error:
Conversion from type 'DBNull' to type 'Date' is not valid.
Here is my code:
'preceded by connection code
Dim sqlcmd As String = "SELECT * from Master WHERE RecNum = #recnum"
'Dim sqlCmd As New OleDb.OleDbCommand("SELECT * from Master WHERE RecNum = #recnum", connection)
Dim FileCommand3 As New OleDb.OleDbCommand(sqlcmd, connection)
FileCommand3.Parameters.AddWithValue("#recnum", user)
Dim Reader3 As OleDb.OleDbDataReader = FileCommand3.ExecuteReader()
If Reader3.Read Then
stock = myCStr(Reader3("StockNum"))
make = myCStr(Reader3("Make"))
color = myCStr(Reader3("Color"))
stockin = myCStr(Reader3("Stockin"))
ucistart = myCStr(Reader3("UCIStartDate"))
repairs = Reader3("Repairs")
tires = Reader3("tiresneeded")
onlot = Reader3("onlot")
sold = Reader3("sold")
year = myCStr(Reader3("year"))
model = myCStr(Reader3("model"))
location = Reader3("location")
srvcRO = myCStr(Reader3("svcROnum"))
ucicompldate = myCStr(Reader3("uciestcompletedate"))
collRO = myCStr(Reader3("collisionROnum"))
other = myCStr(Reader3("other"))
offprop = Reader3("offProperty")
detail = (Reader3("detail")
End If
connection.Close()
SoldCheckBX.Checked = sold
DetailTXTbox.Text = detail
'etc, etc
End Sub
I used the function mycstr to fix the dbnull to string error but it does not seem as simple to adapt to "date" data type
Function myCStr(ByVal test As Object) As String
If isdbnull(test) Then
Return ("")
Else
Return CStr(test)
End If
End Function
try this when you read the values from the reader with all your dates, this will first test to see if the date is dbnull, if it is then it will assign a nothing value and you should get your desired empty cell, otherwise it will show the date:
ucistart = IIf(reader3("UCIStartDate") Is DBNull.Value, Nothing, reader3("UCIStartDate"))
Have you tried using the Convert.IsDBNull function?
Here is the official documentation.