asp.net onClick event for Button - asp.net

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())

Related

I want to update a GridView based off of a value selected from a DropDownList by editing my SqlDataSource

I'm trying to accomplish this by updating the SelectCommand on my SqlDataSource, clearing the GridView, and then reapplying the GridView.DataBind() based off the value in the dropdown. It's not working, and honestly, I'm totally new to this, so I very well could just be doing things incorrectly. Here's some sample code that gives an idea of what I've got:
Protected Sub drp_product_SelectedIndexChanged(sender As Object, e As EventArgs) Handles drp_product.SelectedIndexChanged
grd_ingredientview.DataSource = Nothing
grd_ingredientview.DataBind()
SqlDataSource1.SelectCommand = "blah blah sample select command" + drp_product.SelectedValue
grd_ingredientview.DataSource = SqlDataSource1
grd_ingredientview.DataBind()
End Sub
Again, this doesn't work, and throws up an error, saying: Both DataSource and DataSourceID are defined on 'grd_ingredientview'. Remove one definition.
Any help with this would be appreciated, along with a description for why this isn't working and how your suggestion does. Still learning a lot of this. Thank you!
Well, use code to load up the grid view in the first place, and you can dump the the datasoruce1. (just remove it from the web form). (but ANSWER NO to re-create the fields an update the grid view if prompted).
So yes, use the wizard, let it create that data source. Choose your columns. Test the grid. Ok, now it works. Now that the grid been built?
then delete the Datasourc1 from the page. And then for the property sheet, remove the datasource setting. This one:
So, now we removed that Datasource1 object from the page, and the setting that points to that datasource.
And do the SAME idea with the combo box. Use the wizard, even let it build + add a data source for the combo box. And again, delete the data source and again remove the datasource setting for the combo box just like we did for the gird.
So, now we can (and will) freely use code to fill out the data grid.
So, on page load, the one time (first time) data load, we can do this:
If IsPostBack = False Then
' first time page load - display the grid.
Call LoadGrid("")
Call LoadCombobox
End If
And note, for the combo box? Again, you can freely use the wizards to setup the combo box, but AGAIN remove that data source setting like we did for the grid.
So, now all our code looks like this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack = False Then
' first time page load - display the grid.
Call LoadGrid("")
Call LoadCombobox
End If
End Sub
Sub LoadGrid(Optional strWhere As String = "")
Dim strSQL As String = "SELECT * from tblHotels "
If strWhere <> "" Then
strSQL += " WHERE " & strWhere
End If
Me.GridView1.DataSource = Myrst(strSQL)
Me.GridView1.DataBind()
End Sub
Sub LoadComboBox()
Dim strSQL As String = "SELECT City from tblHotels GROUP BY City"
Me.DropDownList1.DataSource = Myrst(strSQL)
Me.DropDownList1.DataBind()
End Sub
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownList1.SelectedIndexChanged
Dim strWhere As String
strWhere = "City = '" & DropDownList1.SelectedValue & "'"
Call LoadGrid(strWhere)
End Sub
Now the only part I left out was MyRst(). It simply returns a datatable. So, you can use that code (and place it outside in a standard code module.
That way you can use it over and over though out your application, and not have to create a connect object and sql command over and over until you go nuts.
It also means you only EVER use/get/grab a connection string in ONE place in your code, so it is easy to change it when you change the database.
So the handy dandy routine that saves you having over and over to re-write query code and the connection object is this:
Public Function Myrst(strSQL As String, Optional strCon As String = "") As DataTable
' this also allows one to pass custom connection string -
' if not passed, then default
If strCon = "" Then
strCon = My.Settings.TestDatabase3
End If
Using mycon As New SqlConnection(strCon)
Dim oReader As New SqlDataAdapter
Dim rstData As New DataSet
oReader.SelectCommand = New SqlCommand(strSQL, mycon)
Try
oReader.Fill(rstData)
Return rstData.Tables(0)
Catch
Return Nothing
End Try
End Using
End Function
So, with the above simple helper routine, then the code is very easy to write. In fact I find its less code then even desktop code or even writing code in MS-Access.
so the above simple example would select a city from the combo box, and then filter/set the gride to only display that city.
And if you want, you don't have to fill the grid on page load, since the user is about to select a combo box value. So, just comment out the LoadGrid on page load, and only call it when you make a combo (dropdownlist) selection.
As noted, don't forget to set the dropdown list auto-post back = true.
All in all? The above is not a lot of code, and is no more then say doing this for the desktop, or even doing this in Access.

Vb.Net ASP.Net Shopping Cart with cookies

I am building an E-commerce website and everything went great until I started thinking about how I'm going to make my shopping cart, using cookies.
I'm using a datalist to display my products, when a user clicks on a button, I want the product ID to be stored in a cookie so when the user goes to his shopping cart, the cart checks all the ID's in the cookie and then checks in my access database which product it should add.
Does anyone know how I should make this work or have a useful tutorial? Because all the tutorials I found are in java, php, c# etc. but I need to make this in vb.net because it's a school project.
Thanks in advance!
Protected Sub Button1_Click(sender As Object, e As EventArgs)
Dim btnShoppingCart As Button = TryCast(sender, Button)
'get values from datalist
Dim datalistItem As DataListItem = DirectCast(btnShoppingCart.NamingContainer, DataListItem)
'productId
Dim lblProductId As Label = DirectCast(datalistItem.FindControl("lblProductId"), Label)
Dim strProductId As String = lblProductId.Text
Dim objCookie As New HttpCookie("ShoppingCart")
objCookie.Value = strProductId
objCookie.Expires = Now.AddDays(30)
Response.Cookies.Add(objCookie)
End Sub
End Class
If I do it like this, I just get one value saved in the cookie, any way to get multiple values?
If I would use objCookie.Values.add("ID", strProductId) I can only save 1 ID to it, right?
If Request.Cookies("Winkelmand") Is Nothing Then
Dim objCookie As New HttpCookie("Winkelmand")
objCookie.Values.Add(strProductId, strProductId)
objCookie.Expires = Now.AddDays(30)
Response.Cookies.Add(objCookie)
Else
Dim objCookie As HttpCookie = Request.Cookies("Winkelmand")
Dim strControleDubbel As String
strControleDubbel = objCookie.Values.Item(strProductId)
If strControleDubbel = Nothing Then
objCookie.Values.Add(strProductId, strProductId)
Response.Cookies.Add(objCookie)
End If
This code worked!

Asp.net Label not updated after postbck. Need extra refresh

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.

ASP.NET confirm delete in a grid

I need to add a confirm delete action to a grid. the problem is the way the "Delete" link is rendered.
my grid is built in code behind in vb.net.
i have this
colDelete.AllowDelete = True
colDelete.Width = "100"
AddHandler CType(gridSavedForLater, Grid).DeleteCommand, AddressOf dgDeleteSelectedIncident
and the sub is the following
Sub dgDeleteSelectedIncident(ByVal sender As Object, ByVal e As GridRecordEventArgs)
Dim message As String = "Are you sure you want to delete this incident?"
Dim caption As String = "Confirm Delete"
Dim result = System.Windows.Forms.MessageBox.Show(message, caption, Windows.Forms.MessageBoxButtons.OKCancel, Windows.Forms.MessageBoxIcon.Warning)
'If (result = Windows.Forms.DialogResult.Cancel) Then
'Else
' MessageBox("Are you sure you want to delete this incident?")
'Get the VehicleId of the row whose Delete button was clicked
'Dim SelectedIncidentId As String = e.Record("IncidentId")
''Delete the record from the database
'objIncident = New Incidents(SelectedIncidentId, Session("userFullName"))
'objIncident.DeleteIncident()
''Rebind the DataGrid
LoadSavedForLater()
'' End If
End Sub
i need to add a javascript confirm dialog when this sub is called. i can do it with a windows form messagebox but that does not work on the server.
pleae help
joe
You cannot show a MessageBox in ASP.NET since it would be shown on the server. So you need a javascript confirm onclick of the delete button. Therefor you don't need to postback to the server first. You can attach the script on the initial load of the GridView.
A good place would be in RowDataBound of the GridView:
Private Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
Select Case e.Row.RowType
Case DataControlRowType.DataRow
' if it's a custom button in a TemplateField '
Dim BtnDelete = DirectCast(e.Row.FindControl("BtnDelete"), Button)
BtnDelete.OnClientClick = "return confirm('Are you certain you want to delete?');"
' if it's an autogenerated delete-LinkButton: '
Dim LnkBtnDelete As LinkButton = DirectCast(e.Row.Cells(0).Controls(0), LinkButton)
LnkBtnDelete.OnClientClick = "return confirm('Are you certain you want to delete?');"
End Select
End Sub
As an alternative, a common method of notifying users in a web page of a status change (save, delete, update, etc.) is having an update element in your HTML. Basically, a label (or whatever) that you'll set with updates to the user.
"Your changes have been successfully saved." or "An error was encountered when trying to save your update.", for example. You can set the color red for an error or whatever your programming heart desires, stylistically.
I kind of like this approach as a pop-up always feels more like a WinForm thing to me. Either works, so I just thought I'd suggest another approach.

Populate text boxes with data based on redirect from another page

This task is a little out of my reach so i dont even really know where to start...
I want a user to click the command field "select" in my gridview. I then want them to be redirected ( response.redirect()) to an input form that will have its various asp.net text boxes filled with data from that selected item.
I also need the ability to do this logical process:
IF the form is loaded from user
selecting item in gridview THEN
''Populate controls with data from selected gridview item Else Load
form as normal and have the controls
blank endif
I was suggested to use this command for the redirect load...Not sure if its correct:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If InStr(Request.ServerVariables("HTTP_REFERER"), "LogViewer.aspx") Then
'FILL the text boxes with the data from data source!
End If
End Sub
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
EDIT
I got it working thanks to A Tuliper...now how can i get my drop down list to select the correct item based on the data in the gridview??
Private Sub getData(ByVal user As String)
Dim dt As New DataTable()
Dim connection As New SqlConnection("My Connection ")
connection.Open()
Dim sqlCmd As New SqlCommand("SELECT * from AppMaster WHERE RecNum = #recnum", connection)
Dim sqlDa As New SqlDataAdapter(sqlCmd)
sqlCmd.Parameters.AddWithValue("#recnum", user)
sqlDa.Fill(dt)
If dt.Rows.Count > 0 Then
NameTxt.Text = dt.Rows(0)("UserName").ToString()
'''''''''this drop down list needs to be the correct item'''''''''''''''''
'AppDropDownList.SelectedValue = dt.Rows("Application").ToString()
SelectedDateTxt.Text = dt.Rows(0)("DateOfChange").ToString()
DescriptionTxt.Text = dt.Rows(0)("Description").ToString()
SnipetTxt.Text = dt.Rows(0)("Snippet").ToString()
End If
connection.Close()
End Sub
The easiest unhacky method here is to simply create a link in your gridview with the parameters in the URL going to say:
Details
And then in your second page read them:
string param1 = Request.QueryString["Param1"]; //or whatever its called - change it of course

Resources