I have a form which contains a checkbox field. On page load I want to create a separate checkbox for each customer in my Database. The code I have to create the checkboxes for each customer works fine. However, I also want to check in the database if the customer is set to unauthorized if they are then I want to check there box. I also have code for the case where the user checks a box. If a box is checked I update the database setting the unauthorized attribute to true. My problem is when I check a box it works fine and the box is checked, however if I reload the page all the boxes are unchecked. So either my database update is not updating the database or the way I check on page load for checked boxes is incorrect. Any ideas?
The code for the asp checkbox field:
<asp:CheckBoxList id="check1" AutoPostBack="True" TextAlign="Right" OnSelectedIndexChanged="Check" runat="server">
</asp:CheckBoxList>
The Code for the page load:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim sql As String = "SELECT Name, unauthorized, ID FROM Customer ORDER BY Name"
Dim dt As DataTable = db.execDataTableQuery(sql, "Customer")
Dim i As Integer
For i = 0 To dt.Rows.Count - 1
check1.Items.Add(New ListItem(CStr(dt.Rows(i).Item("Name"))))
check1.Items(i).Value = CInt(dt.Rows(i).Item("ID"))
check1.Items(i).Text = CStr(dt.Rows(i).Item("Name"))
If CInt(dt.Rows(i).Item("unauthorized")) = 1 Then
check1.Items(i).Selected = 1
Else
check1.Items(i).Selected = 0
End If
Next
End Sub
The code to update the database:
Sub Check(ByVal sender As Object, ByVal e As EventArgs)
Dim sql As String
If check1.SelectedItem.Selected = 1 Then
sql = "UPDATE Customer SET unauthorized = 1 WHERE ID = #ID"
db.execUpdateQuery(sql, New SqlClient.SqlParameter("#ID", check1.SelectedItem.Value))
Else
sql = "UPDATE Customer SET unauthorized = 0 WHERE ID = #ID"
db.execUpdateQuery(sql, New SqlClient.SqlParameter("#ID", check1.SelectedItem.Value))
End If
End Sub
End Class
You need to wrap you code in Page_Load in a Not Page.IsPostback, otherwise on postback no events are triggered and the selection is lost since you're overwriting it from database.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostback Then
' databind your CheckBoxList '
End If
End Sub
Related
i have some different buttons in a page after clicking them i want them to redirect me to a page that has a gridview , but for each button it gives a different gridview which are generated by datatables . may you help to find ,how can i do that in asp.net, vb ??
i did two pages at the gridview page i made methods that are binding different gridviews for each button , and in the first page where i have the button click events i did the redirecting to this gridview page and called the corresponding methods. it redirects me but doen't give me any gridview at all :(
Call in button action
Response.Redirect("Your Page Name.aspx")
and call in that page a BindGrid Function that you create to bind the gridview
You can redirect by using
Response.Redirect("GridView.aspx")
At the same time you can use only one aspx by using session
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Session.Add("CheckButton", Button1Clicked)
Response.Redirect("GridView.aspx")
End Sub
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Session.Add("CheckButton", Button2Clicked)
Response.Redirect("GridView.aspx")
End Sub
After that at your GridView.aspx on your pageload
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim CheckButton As String = Session("CheckButton")
Dim query As String
If (CheckButton = "Button1Clicked") Then
query = "SELECT * FROM Table1"
Else If (CheckButton = "Button2Clicked") Then
query = "SELECT * FROM Table2"
Else
Response.Write("<script>alert('Error!')</script>")
End If
SqlDataSource1.SelectCommand = query
SqlDataSource1.DataBind()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
' hdncurrpayperiod.Value = test1.ToString
hdnPayperiod.Value = test1.ToString
lblPayPeriodStartDt.Text = test1
Else
lblPayPeriodStartDt.Text = hdnPayperiod.Value
End If
End Sub
Private Sub btnnext_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnnext.Click
' hdnPayPeriodStartDt.Value = ""
Dim datenext As Date
Dim datenextpayperiod As String
datenext = DateTime.Parse(lblPayPeriodStartDt.Text)
datenextpayperiod = datenext.Add(New TimeSpan(14, 0, 0, 0)).ToString("MM/dd/yyyy")
hdnPayperiod.Value = datenextpayperiod
lblPayPeriodStartDt.Text = hdnPayperiod.Value
'hdnPayperiod.Value = lblPayPeriodStartDt.Text.ToString
Response.Redirect("TimeSystem.aspx?PayPeriodStartDate=" + HttpUtility.UrlEncode(hdnPayperiod.Value), False)
End Sub
This is a user control which has calender with next and previous buttons and a label. I get the initial date from the a user control property on initial load(not postback) and on next button click it adds 14 days and displays on label. Everything is fine until I use response.redirect which is hitting not postback and getting the property value again. How can I avoid this. I have to pass the value of date with 14 days added to it in the url but this happens only once as it is refreshing with property value every time It hits response.redirect. Please let me know if I am not clear
In Page_Load in Not IsPostBack block add another 'if' statement that checks if 'PayPeriodStartDate' is present in query string (Request.QueryString). If it is - use that value to set hidden field and label if it isn't use 'test1' value as in your code sample.
When I click on the link in a GridView, it will redirect me to another page and pass a parameter at the same time.
code is as shown at below.
<ItemTemplate>
<asp:LinkButton ID="EditAnnouncement" runat="server" CommandName="Edit" CommandArgument='<%# Bind("annID") %>'>Edit</asp:LinkButton>
</ItemTemplate>
This is the code in vb
Response.Redirect("editmemannouncement.aspx?annID=" + e.CommandArgument)
This is the directed page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
param1 = Request.QueryString("annID")
//search record using the "annID" (will only get 1 record)
TextBox2.Text = reader.Item("anntitle").ToString
User may change the text in TextBox2. In the directed page, there is also a button. When I click on the button, I want to get the changed text in TextBox2. I tried
Dim s As String = TextBox2.Text
but I only get back the original value instead of the changed value. How can I get the changed value from TextBox2.Text
On every page load you set again the TextBox2, so even if you do have change it, you do not see the changes because you overwrite it.
Use the IsPostBack to not overwrite it when you make post back as:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack
param1 = Request.QueryString("annID")
//search record using the "annID" (will only get 1 record)
TextBox2.Text = reader.Item("anntitle").ToString
End If
You need to keep your code inside if(!Page.IsPostBack) section ,
If Not IsPostBack
param1 = Request.QueryString("annID")
//search record using the "annID" (will only get 1 record)
TextBox2.Text = reader.Item("anntitle").ToString
Try to use
IsPostBack : Gets a value that indicates whether the page is being rendered for the first time or is being loaded in response to a postback.
Sub Page_Load
If Not IsPostBack
param1 = Request.QueryString("annID")
TextBox2.Text = reader.Item("anntitle").ToString
End If
End Sub
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