I'm inserting record into the DB after the button has been clicked then on page load I'm checking if the user attended today and display the right label. Problem is it keeps displaying the wrong label after postback, but if I do one refresh i get the correct label displayed.
Protected Sub AttendBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles AttendBtn.Click
Dim con As New SqlConnection
Dim conString As String
conString = ConfigurationManager.ConnectionStrings("attConnection").ConnectionString
con = New SqlConnection(conString)
con.Open()
Dim cmd As New SqlCommand("INSERT INTO Attendance (UserID, Date, Attendance_Cycle, Comments)VALUES (#UserID, #Date, #Attendance_Cycle, #Comments)", con)
cmd.Parameters.AddWithValue("#Date", DateTime.Now)
cmd.Parameters.AddWithValue("#Attendance_Cycle", GlobalVarAndFunc.CurrentCycle(2))
cmd.Parameters.AddWithValue("#Comments", "")
cmd.Parameters.AddWithValue("#UserID", GlobalVarAndFunc.UserID)
cmd.ExecuteNonQuery()
con.Close()
End Sub
and on page load
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If GlobalVarAndFunc.HasAttended Then
attend_LB.Text = "You already attended today"
Else
attend_LB.Text = "Attend now"
End If
End Sub
GlobalVarAndFunc.HasAttended function checks if the User has pressed on the attended button today or not
Please understand the flow of asp page. System will execute your page load before the button click event. So in your case, the moment page_load was called at that time you get the value that is already there in DB because system hasn't executed click event yet. When click event gets execute then your value gets into DB (before this event your DB wasn't updated). So on next refresh you gets the correct value.
Solution : Place page_load code in btn_click event to get the result in one go.
Related
below is my code. this selects the first but 1 and it does not go again
Dim idx As Integer = Me.Dpdtokens.SelectedIndex
If idx <> Me.Dpdtokens.SelectedIndex - 1 Then
Me.Dpdtokens.SelectedIndex = idx + 1
Else
Me.Dpdtokens.SelectedIndex = 0
End If
This works for me:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If cboHotel.SelectedIndex >= 0 Then
' user has selected item, increase by 1
If cboHotel.SelectedIndex < cboHotel.Items.Count - 1 Then
cboHotel.SelectedIndex += 1
End If
Else
' no selection at all - lets start at 0
cboHotel.SelectedIndex = 0
End If
End Sub
So, if user not selected anything (and you allowed that, then selected index is -1. However, by default it will start out with the first item as being selected.
It also not clear what/why your logic grabs selected index, and then on next link checks if they are different? (they can't be).
Edit: ==============================
Also, it not been shown how the dropdown/combo box is being loaded up with values.
For example, I have this on page load:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadCombo()
End If
End Sub
Sub LoadCombo()
Dim rstHotels As DataTable = New DataTable
Using conn As New SqlConnection(My.Settings.TEST4)
Dim strSQL As String =
"SELECT ID, HotelName, City, Province FROM tblHotels ORDER BY HotelName"
Using cmdSQL As New SqlCommand(strSQL, conn)
conn.Open()
rstHotels.Load(cmdSQL.ExecuteReader)
End Using
End Using
cboHotel.DataSource = rstHotels
cboHotel.DataBind()
End Sub
Note VERY careful how I check for is postback. And thus do not re-load the combo box over and over. If you re-load and re-bind the combo box each time on page load, then the selected index etc. will be lost.
and the above advice applies to gridview, listbox etc. In other words, while we have a page load event, we only want to load up controls on FIRST page load. Since all other buttons and events ALSO WILL trigger page load over and over for each post-back, then if we change the index of the combo box, but re-load each time, then the index location will be lost.
Hence, in general, loading up of such controls like combo box, gridviews etc. should only occur one time, and the first time the page loads.
This goal is achieved by checking and using a If Not IsPostBack code stub in the page on-load event.
and thank you for viewing my post. I have a project in vb completed in Visual Studio 2010. Once the user clicks the submit button, I want a popup message that has certain text. I also want an okay and cancel button. If the user clicks okay, the page goes as normal and submits. It cancel is clicked, the page goes back for the user to edit info.
Now, I've tried using msgbox, but it doesn't work server side. From research, I found I prob need to use Jquery. I don't have much experience with that, so any help is appreciated!
Thanks,
Josh
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
If (Not Page.IsPostBack) Then
Me.btnSubmit.Attributes.Add("onclick", "return confirm('Please note that what you have entered will be used to auto-generate the flyer. Also, submissions less than 30 days from the date entered may be denied.');")
End If
Dim objRequestID As Object = Nothing
Dim intRequestID As Integer = 0
Try
If ValidateForm() Then
Using objConnection As SqlConnection = util.GetConnection()
Using objTransaction As SqlTransaction = objConnection.BeginTransaction
Using objCommand As SqlCommand = New SqlCommand("Request_Insert", objConnection)
With objCommand
.CommandType = Data.CommandType.StoredProcedure
.Transaction = objTransaction
.Parameters.Add("#CourseTypeID", Data.SqlDbType.Int).Value = util.CourseRequestType.PIE
.Parameters.Add("#SponsorName", Data.SqlDbType.NVarChar, 50).Value = SponsorName.Text.Trim
.Parameters.Add("#SponsorPhone", Data.SqlDbType.NVarChar, 20).Value = SponsorPhone.Text.Trimenter code here
You need to put client button onclick event at server Page_Load event.
When you reach to btnSubmit_Click, it is too late.
Protected Sub Page_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
If (Not Page.IsPostBack) Then
Me.btnSubmit.Attributes.Add("onclick", "return confirm('Please...');")
End If
End Sub
you can call this javascript on button click
<script>
function myFunction()
{
alert("I am an alert box!");
}
</script>
Good afternoon people have been trying to fill a dropdown using a sql command, until so good, when I click on the dropdown it shows all the items, but when I try to click on an item in the dropdown it always returns the first item in the dropdown .... follows the codes, what i want to do is get the selected value and item from the dropdown and save it on a label for future use.
I appreciate all the support possible,
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
utilizador.Text = Me.Context.User.Identity.Name
If (Not Page.IsPostBack) Then
escolhePerfil()
End If
'DropDownPerfil.DataBind()
lbperfil2.Text = DropDownPerfil.SelectedItem.Text
lbnome.Text = DropDownPerfil.SelectedValue
End Sub
Function escolhePerfil() As Boolean
Dim connstring As String = "Data Source=10.2.24.17;Persist Security Info=True;User ID=sa;Password=Pr0dUn1C0$qL;database=ePrimavera"
Dim SQLData As New System.Data.SqlClient.SqlConnection(connstring)
Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT u.WindowsUser,u.Email ,g.Description, u.Login FROM [ePrimavera].[dbo].[PLT_Users] as u,[ePrimavera].[dbo].[PLT_UserGroups] as ug, [ePrimavera].[dbo].[PLT_Groups] as g where u.ID = ug.UserID And ug.GroupID = g.ID and u.WindowsUser like 'bancounico\" & utilizador.Text & "'", SQLData)
SQLData.Open()
Dim dtrReader As System.Data.SqlClient.SqlDataReader = cmdSelect.ExecuteReader()
If dtrReader.HasRows Then
DropDownPerfil.DataValueField = "Login"
DropDownPerfil.DataTextField = "Description"
DropDownPerfil.DataSource = dtrReader
DropDownPerfil.DataBind()
End If
SQLData.Close()
Return True
End Function
.aspx
<asp:DropDownList ID="DropDownPerfil" runat="server"
Height="16px" Width="202px" CssClass="DropBorderColor">
</asp:DropDownList>
try the following code:
Protected Sub DropDownPerfil_SelectedIndexChanged(sender As Object, e As EventArgs)
lbperfil2.Text = DropDownPerfil.SelectedItem.Text
lbnome.Text = DropDownPerfil.SelectedValue
End Sub
The problem is that you are trying to get the value "too early". The value is not valid in the Page_Load, since the control's OnLoad event fired after the Page's OnLoad (Page_Load) event.
The way, what the others wrote the correct, since the Event handlig section (inclueding control's onchanged event) will process after the Load section.
For more details check the offical ASP.NET life cycle site in the MSDN
The likely reason is that some (if not all) the values you are assigning to the DropDownList for Login are occur more than once.
When you then select an item in the DDL, if the value of that item occurs more than once, the selected index will highlight the first instance. To test this, comment out DropDownPerfil.DataValueField = "Login"
I am sure upon selection, it will highlight the correct item you intended on selecting.
I have created a form to update an access DB table. My issue is that when the text in the text boxes is changed and the form is submitted, the .text values stay the same as they were when the datareader loaded them on the page load event. How can I submit the values that the user updates, not what is already there from page load.
Code:
Public Property vehicleid As Integer
Public Property connstring As String = "myconnectionstring..."
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
vehicleid = Integer.Parse(Request.QueryString("vehicID"))
Dim svEnterdate, stocknum, make, model, color As String
Dim conn As New OleDbConnection(connstring)
Dim sql As String = "select * from vehicle where vehicleid=#vid"
Dim cmd As New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#vid", vehicleid)
conn.Open()
Dim dr As OleDbDataReader = cmd.ExecuteReader
While dr.Read
svEnterdate = dr("enterdate").ToString()
stocknum = dr("stock_num").ToString()
make = dr("make").ToString()
model = dr("model").ToString()
color = dr("color").ToString()
End While
conn.Close()
EnterDateTXT.Text = svEnterdate
StockNumTXT.Text = stocknum
MakeTxt.Text = make
ModelTXT.Text = model
ColorTxt.Text = color
End Sub
'inbetween these 2 events the user can manipulate all the controls .text values, yet the
' .text values of the submitted controls below are the same as the ones filled by the
'datareader
Protected Sub SubmitBTN_Click(ByVal sender As Object, ByVal e As EventArgs) Handles SubmitBTN.Click
Dim conn As New OleDbConnection(connstring)
Dim sql As String = "UPDATE Vehicle" & _
" SET stock_num=#stock, make=#make, model=#model, color=#color, enterdate=#enter " & _
"WHERE vehicleid=#vid"
Dim cmd As New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#vid", vehicleid)
cmd.Parameters.AddWithValue("#stock", StockNumTXT.Text)
cmd.Parameters.AddWithValue("#make", MakeTxt.Text)
cmd.Parameters.AddWithValue("#model", ModelTXT.Text)
cmd.Parameters.AddWithValue("#color", ColorTxt.Text)
cmd.Parameters.AddWithValue("#enter", EnterDateTXT.Text)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Sub
In your page load code, Check For Post back
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
' Write your code to read data from database here
End
End Sub
If you dont check for postback in your page load event, Everytime when you click the submit button, It is going to excute the code in your page load ( load the content again to the text box) first. So whatever you entered in the textbox will be overwritten by the content form the database and that will be saved back again to the database.
To undestand this. Put a breakpoint in your Page_load event code and another in your button click event code. Now enter some value in textbox and click the button and see whether your code block in pageload is executing or not.
Checking the Postback check in your page_load will fix the problem.
http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx
I have a button on a web page that when clicked connects to my SQL server and runs a stored procedure. The buttons works fine (It simply pushes data into a database table).
I’m new to .NET programming and I’m having trouble finding the right code ideas to add on to the current code for the button I already have.
Ideally, I would just like to have a message box to appear when the button is clicked to notify the user that the ‘data has been saved’ with just the "OK" option and for the user to then be redirected to the home page.
I also need to make sure that this button is only pressed once or deactivated once it has been pressed that day as I don’t want the user to press the button multiple times.
Here is my current code for the button:
Protected Sub btnAddRawData_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddRawData.Click
'database conn, this is linked to the web config file .AppSettings
Using dbconnection As New SqlConnection(ConfigurationManager.AppSettings("dbconnection"))
dbconnection.Open()
'command to state the stored procedure and the name of the stored procedure
Using dbcommand As SqlCommand = dbconnection.CreateCommand
With dbcommand
.CommandType = CommandType.StoredProcedure
.CommandText = "GasNominationsRawData_Insert"
'simply execute the query
dbcommand.ExecuteNonQuery()
'I need to add some code for the button here and...
'redirect to the main home page
Response.Redirect("~/default.aspx?")
End With
End Using
End Using
End Sub
Any ideas and suggestions would be much appreciated.
Regards,
Betty.
function success()
{
alert('Your data has been saved successfully)';
window.location.href='Default.aspx';
}
On code behind, right after this line:
dbcommand.ExecuteNonQuery()
Do this:
Dim cs As ClientScriptManager = Page.ClientScript
Dim csname1 As [String] = "PopupScript"
Dim cstype As Type = Me.[GetType]()
Dim cstext1 As New StringBuilder()
cstext1.Append("success();")
cs.RegisterStartupScript(cstype, csname1, cstext1.ToString())