I used to have this working as so....
Dim AnnEnt As Label = FormView1.FindControl("Holiday_RemainingLabel")
txtNoofDays.Text.ToString()
AnnEnt.Text.ToString()
If txtNoofDays.Text >= AnnEnt.Text Then
lblHolRequestResponse.Text = "Your holiday could not be saved"
Else
I've recently change it to this and it no longer works
Dim remain As TextBox = FormView1.FindControl("Holiday_RemainingTextBox")
txtNoofDays.Text.ToString()
remain.Text.ToString()
If txtNoofDays.Text >= remain.Text Then
lblHolRequestResponse.Text = "Your holiday could not be saved"
Else
What is the difference between the textbox in the formview and label in the formview to keep this from working?
i've since tried...
Dim days = txtNoofDays.Text
days.ToString()
AnnEnt.Text.ToString()
remain.Text.ToString()
If remain.Text.ToString < days.ToString Then
lblHolRequestResponse.Text = "Your holiday could not be saved"
If you want to compare strings numerical, cast them to numbers.
For example(asssuming they are ints):
Dim remain As TextBox = FormView1.FindControl("Holiday_RemainingTextBox")
Dim remaining = Int32.Parse(remain.Text)
Dim numOfDays = Int32.Parse(txtNoofDays.Text)
If numOfDays >= remaining Then
lblHolRequestResponse.Text = "Your holiday could not be saved"
End If
Int32.Parse Method
Otherwise you're comparing alphabetically.
String.CompareTo Method
Related
I have a ballot for a election system and I need to loop through all the checkboxes on the ballot to see if they are checked or unchecked. You can only select (for example) 1 of the 5 boxes available. I am stuck and can not for the life of me figure this out. The following code is my function that runs when the user clicks the submit button.
This code works and submit my ballot but does not check the number of checkboxes checked.
For Each row As Object In candidatesTable.Rows
If row(1) = ballot_ID Then
Dim checkBox_ID = row(0)
Dim CB As New CheckBox()
CB = mainBallotDiv.FindControl(checkBox_ID)
If CB.Checked Then
Dim addVote As Integer = row("votes")
addVote += 1
candidatesAdapter.addVoteToCandidate(addVote, row(0))
Dim section_ID As Integer = row(2)
Dim voter As String = userGnumber
Dim vote As Integer = checkBox_ID
Dim hasVoted As Boolean = True
votesAdapter.InsertVotes(ballot_ID, section_ID, voter, vote, hasVoted)
End If
End If
Next
Response.Redirect("~/voting/voted.aspx")
I have added a couple things to try and get this to run correctly but no luck, my code currently is the following.
Dim checkedCount As Integer
For Each row As Object In candidatesTable.Rows
If row(1) = ballot_ID Then
Dim checkBox_ID = row(0)
Dim CB As New CheckBox()
CB = mainBallotDiv.FindControl(checkBox_ID)
Dim section_idFromCB As Integer = candidatesAdapter.getsectionIDfromcandidateID(CB.ID)
Dim voteLimit As Integer = sectionsAdapter.votesbysectionid(section_idFromCB)
If CB.Checked Then
checkedCount += 1
Debug.Write(checkedCount)
If checkedCount > voteLimit Then
' error
Response.Write("<script language=""javascript"">alert('You can not select that many check boxes.');</script>")
Response.Redirect(Request.RawUrl)
Else
' pass
For Each Nrow As Object In candidatesTable.Rows
If Nrow(1) = ballot_ID Then
Dim NcheckBox_ID = row(0)
Dim NCB As New CheckBox()
NCB = mainBallotDiv.FindControl(NcheckBox_ID)
If NCB.Checked Then
Dim addVote As Integer = row("votes")
addVote += 1
candidatesAdapter.addVoteToCandidate(addVote, row(0))
Dim section_ID As Integer = row(2)
Dim voter As String = userGnumber
Dim vote As Integer = checkBox_ID
Dim hasVoted As Boolean = True
votesAdapter.InsertVotes(ballot_ID, section_ID, voter, vote, hasVoted)
End If
End If
Next
Response.Redirect("~/voting/voted.aspx")
End If
End If
End If
Next
Any help would be appreciated, and thanks in advance.
Here is my recommendation...
You can put them in a List(Of CheckBox) then you can access them anytime as needed as well as get any property you would need.
Dim lstChecked As New List(Of CheckBox)
lstChecked = divcontrol.Controls.OfType(Of CheckBox).Where(Function(ch) ch.Checked = True).ToList
lstChecked would be any CheckBox that would be checked...
For Each checkBox In Me.Controls.OfType(Of CheckBox)
' do something
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'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)
Im doing this project for an online test in ASP.NET in VB im using Microsoft visual studios 2012.
Im trying to get a loop going through my textboxes and check them against a word this will be change to be validated against a database to see if the answer are correct but when I do my loop I cannot get my text from the textbox.
Please see below
Private Sub GoGoGo()
Dim Textboxname As String '
Dim textbox As Object
Dim TextboxText As Object
Dim Labelname As String
Dim label As Object
Dim LabelText As Object
Dim Number As Integer = 1
Dim MaxTime As Integer = 9
Dim Currentloop As Integer = 1
For check As Integer = Currentloop To MaxTime
If Currentloop <= MaxTime Then
Textboxname = "TextQ" + Number
textbox = Textboxname
TextboxText = textbox
textbox.ReadOnly = True
End If
If Currentloop <= MaxTime Then
Labelname = "Label" + Number
label = Labelname
LabelText = label.Text
label.Visible = True
End If
Number = Number + 1
If TextboxText = "" Then
label.Text = "no imput"
label.ForeColor = Drawing.Color.Black
End If
If TextboxText = "server" Then
label.Text = "Correct"
label.ForeColor = Drawing.Color.Green
End If
If TextboxText = "Wrong" Then
label.Text = "Wrong"
label.ForeColor = Drawing.Color.Red
End If
If check = 9 Then
Exit For
End If
Next
End Sub
It looks like you are trying to use the string identifier of the control in place of the the actual control. Instead, you should take this identifier and search for the actual control on the page. You can do this using the FindControl method
Your function would therefore look something like (not compile tested):
Private Sub GoGoGo()
'
Dim oTextBox As TextBox
Dim oLabel As Label
Dim MaxTime As Integer = 9
Dim Currentloop As Integer = 1
For check As Integer = Currentloop To MaxTime
If Currentloop <= MaxTime Then
'NB You may have to use a recursive call to FindControl. See below.
oTextBox = CType(Page.FindControl("TextQ" & CStr(check)), TextBox)
OTextBox.ReadOnly = True;
End If
If Currentloop <= MaxTime Then
'NB You may have to use a recursive call to FindControl. See below.
oLabel = CType(Page.FindControl("Label" & CStr(check)), Label)
oLabel.Visible = True
End If
If oTextBox.Text = "" Then
oLabel.Text = "no imput"
oLabel.ForeColor = Drawing.Color.Black
End If
If oTextBox.Text = "server" Then
oLabel.Text = "Correct"
oLabel.ForeColor = Drawing.Color.Green
End If
If oTextBox.Text = "Wrong" Then
oLabel.Text = "Wrong"
oLabel.ForeColor = Drawing.Color.Red
End If
Next
End Sub
Some notes:
You don't need all of those variables. Instead, just find the actual controls, and interact with the properties directly - just check the TextBox.Text value when you need to, and set the Label.text property directly. The set is especially important as you want to update the original control property so it is shown on the page.
Similarly, you don't need Number - you can use check as this is your loop counting variable.
Whether you use the + operator or the & operator for string concatenation is up to you. There's already a good question and several answers here.
You also don't need the exit condition for the loop - the loop will exit as soon as you reach MaxTime. If you want it to exit early, just vary your To condition (e.g. Currentloop To MaxTime - 1)
UPDATE:
Page.FindControl will only work with controls that are immediate children of the root element on the page. Instead, you should try calling FindControl recursively. You should also make sure that a control with the id TextQ1 exists - look in the HTML source for the page on the client to make sure a TextBox with this id exists.
There are many examples of this on the net. Here's a VB.Net version (source: http://www.pavey.me/2007/09/recursive-pagefindcontrol-for-vbnet.html) that you can add to your page:
Public Function FindControlRecursive(Of ItemType)(ByVal Ctrl As Object, ByVal id As String) As ItemType
If String.Compare(Ctrl.ID, id, StringComparison.OrdinalIgnoreCase) = 0 AndAlso TypeOf Ctrl Is ItemType Then
Return CType(Ctrl, ItemType)
End If
For Each c As Control In Ctrl.Controls
Dim t As ItemType = FindControlRecursive(Of ItemType)(c, id)
If t IsNot Nothing Then
Return t
End If
Next
Return Nothing
End Function
Your line in the code above would then become:
oTextBox = FindControlRecursive(of TextBox)(Page.Controls(0), "TextQ" & CStr(check))
You'd also need to do the same for the Label control.
It Look like you are using only name istead of textbox try with the code below
Private Sub GoGoGo()
Dim Textboxname As String '
Dim textbox As TextBox
Dim TextboxText As Object
Dim Labelname As String
Dim label As Object
Dim LabelText As Object
Dim Number As Integer = 1
Dim MaxTime As Integer = 9
Dim Currentloop As Integer = 1
For check As Integer = Currentloop To MaxTime
If Currentloop <= MaxTime Then
Textboxname = "TextQ" + Number
textbox = Ctype(Me.Controls(Textboxname), TextBox)
TextboxText = textbox.Text
textbox.ReadOnly = True
End If
If Currentloop <= MaxTime Then
Labelname = "Label" + Number
label = Labelname
LabelText = label.Text
label.Visible = True
End If
Number = Number + 1
If TextboxText = "" Then
label.Text = "no imput"
label.ForeColor = Drawing.Color.Black
End If
If TextboxText = "server" Then
label.Text = "Correct"
label.ForeColor = Drawing.Color.Green
End If
If TextboxText = "Wrong" Then
label.Text = "Wrong"
label.ForeColor = Drawing.Color.Red
End If
If check = 9 Then
Exit For
End If
Next
End Sub
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.