In my user control, I have a text boxes that I used to create a new membership user. Each listbox has a datasource set to membership.getallusers() to fill the listbox. When the listbox index is changed, it populates the text boxes to allow editing. What I want to accomplish is: have each user listbox refresh to show the new user that gets created. Even though I call databind() after successfully creating the user, it doesn't update. On the form load I check if listbox.items.count < 1, then call databind(), which does work correctly. Any ideas?
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If ListBox3.Items.Count < 1 Then
For Each item As MembershipUser In Membership.GetAllUsers(0, Membership.GetAllUsers.Count + 1, Membership.GetAllUsers.Count)
ListBox3.Items.Add(item.UserName)
Next
Label1.Text = ListBox3.Items.Count
username = ListBox3.Items(0).ToString
Else
ListBox1.DataBind()
ListBox3.DataBind()
End If
user = Membership.GetUser
ListBox1.DataSource = Membership.GetAllUsers
ListBox1.DataBind()
ListBox2.DataSource = Roles.GetAllRoles
ListBox2.DataBind()
' ListBox3.DataSource = Membership.GetAllUsers
'ListBox3.DataBind()
End Sub
Protected Sub ListBox3_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox3.SelectedIndexChanged
txtUsername.Text = user.UserName
txtEmail.Text = user.Email
txtQuestion.Text = user.PasswordQuestion
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try'Creates a new user
Dim status As System.Web.Security.MembershipCreateStatus
Membership.CreateUser(txtUsername.Text, txtPassword.Text, txtEmail.Text, txtQuestion.Text, txtAnswer.Text, True, status)
Label1.Text = "User " & txtUsername.Text & " was created"
'ListBox3.Items.Clear()
ListBox1.DataBind()
'ListBox3.DataBind()
Catch ex As Exception
Label1.Text = "Error:" & ex.Message
End Try
End Sub
You need to set the datasource again before you do the databind, like so:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try'Creates a new user
Dim status As System.Web.Security.MembershipCreateStatus
Membership.CreateUser(txtUsername.Text, txtPassword.Text, txtEmail.Text, txtQuestion.Text, txtAnswer.Text, True, status)
Label1.Text = "User " & txtUsername.Text & " was created"
'ListBox3.Items.Clear()
ListBox1.DataSource = Membership.GetAllUsers() ' Necessary because the DB has changed
ListBox1.DataBind()
'ListBox3.DataBind()
Catch ex As Exception
Label1.Text = "Error:" & ex.Message
End Try
End Sub
When you call databind, you might think that that's the moment the Listbox will call the method you gave it as a datasource, but that's not the case. The moment you assign the datasource, the data is retrieved. When you actually call the Databind-method, the Listbox will create the necessary internal controls
Related
im trying to get value(true or false) from database but i want to select from role(DropDownList) to display if had permission or not in section
dropdownlist and checkboxlist using entitdatasource
i try this ( DropdownList(ddlRole))
Protected Sub ddlRole_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ddlRole.SelectedIndexChanged
Using context As New AGIP_dbModel.AGIP_dbEntities()
For Each oItem As ListItem In ckSection.Items()
Dim objPerm As tbl_permission = New tbl_permission()
oItem.Value = objPerm.pre_status
Next
End Using
End Sub
This how submite button work(Store in database)
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
Using context As New AGIP_dbModel.AGIP_dbEntities()
Dim id As Integer = ddlRole.SelectedValue
Try
Dim obj = context.tbl_permission.Where(Function(u) u.role_id = id)
For Each permission As tbl_permission In obj.ToList
context.tbl_permission.DeleteObject(permission)
context.SaveChanges()
Next
Catch ex As Exception
End Try
For Each oItem As ListItem In ckSection.Items()
Dim objPerm As tbl_permission = New tbl_permission()
objPerm.role_id = ddlRole.SelectedValue
objPerm.pre_status = oItem.Selected
objPerm.section_id = oItem.Value
context.tbl_permission.AddObject(objPerm)
context.SaveChanges()
Next
Response.Redirect("permission.aspx")
End Using
End Sub
tbl_role
tbl_section
tbl_permission relationship with role and section
I'm not familiar with usage of Entity yet so I hope you can get what I'm trying to do here.
Also not sure if checkbox has a Caption or Text property, kindly check.
Protected Sub ddlRole_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ddlRole.SelectedIndexChanged
Using context As New AGIP_dbModel.AGIP_dbEntities()
For Each oItem As ListItem In ckSection.Items()
Dim objPerm As tbl_permission = New tbl_permission()
If objPerm.section_name = oItem.Caption Then 'Check if the permission record is same with the caption of the current checkbox in iteration
oItem.Checked = objPerm.pre_status
End If
Next oItem
End Using
End Sub
You also need to modify your SQL query on returning the permission records to include the section_name if you haven't already.
Finally found The Answer:
Protected Sub ddlRole_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ddlRole.SelectedIndexChanged
Using context As New BWJO_dbModel.BWJO_dbEntities
Try
For Each secTionItem As ListItem In ckSection.Items
secTionItem.Selected = False
For Each oItem As ListItem In ckSection.Items
Dim PermObj = context.tbl_permission.Any(Function(u) u.role_id = ddlRole.SelectedValue And u.permission_status = True And u.section_id = oItem.Value)
If PermObj = True Then
oItem.Selected = True
End If
Next
Next
Catch ex As Exception
End Try
End Using
End Sub
End Class
I have a page on the website that display a client details in text boxes.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not page.IsPostBack Then
Dim dh As New Datahandler
Dim CI As ClientInfomation = dh.GETClientInfomationWithClientID(Session("ClientID"))
txtClientID.Text = Session("ClientID")
txtCompany.Text = CI.Company
txtEmail.Text = CI.Email
txtPassword.text = CI.Password
dtSubcriptionEndDate.Text = CI.SubscriptionEndDate
txtContactName.Text = CI.ContactName
txtTelephoneNum.Text = CI.Telephone.ToString()
End If
The above code works,the code gets the client data from the database in the GETClientInfomationWithClientID(Session("ClientID")) and loads the data into a class, and from the class I load the data into the text boxes.
Here is where my problem starts. A user will now change his details in the text boxes and click the 'Save changes' button invoking the butSaveChanges_Click Event.
Protected Sub butSaveChanges_Click(sender As Object, e As EventArgs) Handles butSaveChanges.Click
Dim dh As New Datahandler
Dim CI As New ClientInfomation With {.ClientID = txtClientID.Text,
.Company = txtCompany.Text,
.ContactName = txtContactName.Text,
.Email = txtEmail.Text,
.Password = txtPassword.Text,
.SubscriptionEndDate = dtSubcriptionEndDate.Text,
.Telephone = txtTelephoneNum.Text}
If dh.SaveUserProfileChanegs(CI) = True Then
ClientScript.RegisterStartupScript(Me.[GetType](), "alert", "alert('Changes has been saved')", True)
Else
ClientScript.RegisterStartupScript(Me.[GetType](), "alert", "alert('Changes could not be saved')", True)
End If
End Sub
I just wanted to load the changed text values into the class, and load the class in the SaveUserProfileChanegs(CI) function that updates the new values in the database.
When the butSaveChanges_Click event is invoked I get a "(1) : error BC32022: 'Public Event Click As EventHandler' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event."
I have response form in asp.net. I want on send button click the button text should change from send to please wait & once it is send it should back to it's default value text 'send'. can any one help?
code
Protected Sub submit_client_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submit_client.Click
Try
Dim pattern As String
pattern = "^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*#([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$"
If Regex.IsMatch(TextBox3.Text, pattern) Then
Label2.Text = ""
Else
Label2.Text = "Not a valid Email address "
End If
Dim emails As New List(Of String)()
generate.Visible = True
clear.Visible = True
SendHTMLMail()
'For Each item As ListViewItem In lvCustomers.Items
' Dim ck As CheckBox = DirectCast(item.FindControl("CheckBox1"), CheckBox)
' If ck.Checked Then
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
try like this:
MyButton.Text="Sending"
SendHTMLMail()
Thread.Sleep(3000) // add this & remove SendHTMLMail() for testing
MyButton.Text="Send"
I select values from database into textboxes on page load. Then when I change them and want to update the database, values are same as original values. For example I select name Robin Hood into TextBoxName, change it to Bill Gates, but the value of textbox on updating is still Robin Hood. How can I fix this behavior?
However this applies only to textboxes with TextMode="SingleLIne" Or "MultiLine". When textbox has TextMode="Url" for example, it works fine.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Bind
Try
Using conn As New SqlConnection(connStr)
Dim cmd As SqlCommand = conn.CreateCommand
cmd.CommandText = "SELECT * FROM Profiles WHERE (ProfileId = #ProfileId)"
cmd.Parameters.AddWithValue("#ProfileId", Request.QueryString("id"))
conn.Open()
Dim rd As SqlDataReader = cmd.ExecuteReader()
While rd.Read()
ProfileImage.ImageUrl = rd.Item("ProPicUrl")
txtName.Text = rd.Item("Name")
txtCity.Text = rd.Item("City")
drpRegion.Items.FindByText(rd.Item("Region")).Selected = True
txtAge.Text = rd.Item("Age")
RadioButtonList1.Items.FindByText(rd.Item("Sex")).Selected = True
txtLink.Text = rd.Item("Link")
txtPhone.Text = rd.Item("Phone")
txtAbout.Text = rd.Item("About")
txtMotto.Text = rd.Item("Motto")
txtGoal.Text = rd.Item("Goal")
txtHobby.Text = rd.Item("Hobby")
End While
conn.Close()
End Using
Catch ex As Exception
End Try
End Sub
Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim fileUrl As String = "~/ProPics/"
Dim name As String = txtName.Text
Try
'Save profile picture
Try
If FileUpload1.HasFile Then
fileUrl += FileUpload1.FileName
FileUpload1.SaveAs(Server.MapPath(fileUrl))
Else
fileUrl = ProfileImage.ImageUrl
End If
Catch ex As Exception
UploadMessage.Text = "Nastala chyba při nahrávání obrázku." + vbCrLf + "Chybové hlášení: " + ex.Message
End Try
Using conn As New SqlConnection(connStr)
Dim cmd As SqlCommand = conn.CreateCommand
cmd.CommandText = "UPDATE Profiles SET Name = #Name, ProPicUrl = #Url, City = #City, Region = #Region, Age = #Age, Sex = #Sex, Link = #Link, Phone = #Phone, About = #About, Motto = #Motto, Goal = #Goal, Hobby = #Hobby WHERE (ProfileId = #ProfileId)"
cmd.Parameters.AddWithValue("#Url", fileUrl)
cmd.Parameters.AddWithValue("#Name", name)
cmd.Parameters.AddWithValue("#City", txtCity.Text)
cmd.Parameters.AddWithValue("#Region", drpRegion.SelectedItem.Text)
cmd.Parameters.AddWithValue("#Age", txtAge.Text)
cmd.Parameters.AddWithValue("#Sex", RadioButtonList1.SelectedItem.Text)
cmd.Parameters.AddWithValue("#Phone", txtPhone.Text)
cmd.Parameters.AddWithValue("#Link", txtLink.Text)
cmd.Parameters.AddWithValue("#About", txtAbout.Text)
cmd.Parameters.AddWithValue("#Motto", txtMotto.Text)
cmd.Parameters.AddWithValue("#Goal", txtGoal.Text)
cmd.Parameters.AddWithValue("#Hobby", txtHobby.Text)
cmd.Parameters.AddWithValue("#ProfileId", Request.QueryString("id"))
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
'Refresh page
Response.Redirect(Request.RawUrl)
End Using
Catch ex As Exception
End Try
End Sub
You need to add a check for IsPostBack property of the page when you execute code in the Page_Load event.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
if Not PostBack Then
...... code to execute only the first time the Page_Load is called
Try
End Try
Catch ex As Exception
End Try
End If
.. code to execute every time....
End Sub
When your user clicks on a button with Runat=Server then the button calls the event on the server side code, but this cause a new call to Page_Load.
Actually your code reloads from the database the original value everytime the Page_Load event executes and thus your button click event code sees the original value from the database instead of the modified value.
This article on the Page Life Cycle could be useful here
I have a CheckBoxList on my page that isn't behaving very well.
The idea is that once the submit button on the form is clicked, the app should clear the database table of all rows pertaining to the specific user and then re-insert new ones based on the user's CheckBoxList selections.
The problem is that regardless of whether or not any (or all) items in the CheckBoxList are selected, the app keeps getting Selected = False.
Here's my code:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
loadRegions()
End Sub
Private Sub loadRegions()
Dim db As New Database
Dim sql As String = "select * from regions"
Dim dr As MySqlDataReader = db.execDB(sql, "Text", Nothing, "DataReader", False)
If dr.HasRows Then
cblRegion.DataSource = dr
cblRegion.DataTextField = "regionname"
cblRegion.DataValueField = "regionid"
cblRegion.DataBind()
End If
dr.Close()
End Sub
Protected Sub btnRegister_Click(sender As Object, e As System.EventArgs) Handles btnRegister.Click
' ============================================================
' There's more code in here, but it's irrelevant to this paste
' ============================================================
Dim sql As String = "delete from userregions where userid = " & lblUserID.Text & ";"
For i As Integer = 0 To cblRegion.Items.Count - 1
If cblRegion.Items(i).Selected Then
sql &= "insert into userregions (userid, regionid)" & _
"values(" & UserID & ", " & cblRegion.Items(i).Value & ")"
db.execDB(sql, "Text", Nothing, "None", False)
End If
Next
End Sub
For the record
I'm aware of the potential for SQL Injection here. I'll be going over to using Parameters as soon as I have the loop working.
Thanks for your time.
Any help will be greatly appreciated.
You only need to call loadRegions on the initial load and not on postbacks:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
loadRegions()
End If
End Sub
Otherwise you'll lose changed values and events are not triggered.
Add this line of copde "If IsPostBack Then Return" in Page_Load method.
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If IsPostBack Then Return
loadRegions()
End Sub
In page loaded, write the following:
If Not IsPostBack
loadRegions()
End If