I am trying to populate My RadioButtonList values from database. That is working for me. But I am not getting how should I keep one predefined values in database to be selected by default in radiobuttonList. I have list of cities in my db table. One city I want to be selected when page loads. Following is my code
Private Sub MasterPage_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Me.PopulateCities()
End Sub
Private Sub PopulateCities()
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "Select cityName from cities where status = 'active' order by cityName"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("cityName").ToString()
item.Value = sdr("cityName").ToString()
item.Selected = Convert.ToBoolean(sdr("IsSelected"))
locationSelector.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
If you database cities table contains IsSelected field then you need to change your query like this
Select cityName, IsSelected from cities where status = 'active' order by cityName
Elese you need to update your first list item
locationSelector.Items(0).Selected = True
Related
I have masterpage & content page. In master Page I have DropDownList of Cities which Gets cities from database. And in my content page I DropDownList Of Areas which also comes from database. Now Suppose If My city gets changed then desire area related to that particular selected city should also get changed. I have manage my db tables properly & passing correct query as well. But DropDownList Of areas doesn't gets refreshed if City DropDownList gets changed. Following code I am trying.
MasterPage
Private Sub MasterPage_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.PopulateCities()
If Not IsPostBack Then
If Session("masterLocation") Is Nothing Then
Session("cityName") = "Pune"
Else
locationSelector.Text = Session("masterLocation").ToString()
End If
End If
locationPopupActivator.Text = locationSelector.SelectedValue.ToString
End Sub
Private Sub PopulateCities()
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "Select cityName from cities where status = 'active' order by cityName"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("cityName").ToString()
item.Value = sdr("cityName").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
locationSelector.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
End Sub
ContentPage
Private Sub hospitals_PreRender(sender As Object, e As EventArgs) Handles Me.PreRender
If Not IsPostBack Then
Me.PopulateAreas()
End If
End Sub
Private Sub PopulateAreas()
areasList.Items.Clear()
Dim citySelector As RadioButtonList = Page.Master.FindControl("locationSelector")
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "Select * from areas where areaCity like '" + citySelector.SelectedItem.ToString + "%'"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("areaName").ToString()
item.Value = sdr("areaName").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
areasList.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
areasList.Items.Insert(0, New ListItem("All Area", "All"))
End Sub
Everything in your code is fine just make changes On Pre_Render event of your content page
If IsPostBack Then
Me.PopulateAreas()
End If
Make this changes. Hope this will solve your problem.
I have bind my dropdownlist with database. But on each PostBack the items in dropdownlist gets repeat again.
e.g.
OnPage Load I have this items in dropdownlist 1,2,3,4.. etc Now suppose page gets postBack then it looks like 1,2,3,4,1,2,3,4
Vb code
Private Sub hospitals_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.PopulateAreas()
End Sub
Private Sub PopulateAreas()
If IsPostBack Then
Dim citySelector As DropDownList = Page.Master.FindControl("locationSelector")
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "Select * from areas where areaCity Like '" + citySelector.SelectedItem.ToString + "%'"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("areaName").ToString()
item.Value = sdr("areaID").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
areasList.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
End If
UPDATE
I have master page which has dropdownlist of cities. I am using masterpage control to mycontent page like below.
Dim citySelector As DropDownList = Page.Master.FindControl("locationSelector")
Now in my PopulateArea() class there is query in which WHERE clause have cityselector. So according to city my area gets fetched.
Call your function inside not postback event so that the dropdown is not called on postback events(which fills it everything).
Private Sub hospitals_Load(sender As Object, e As EventArgs) Handles Me.Load
if ispostback = false then
Me.PopulateAreas()
end if
End Sub
its pretty simple.. the page load event is triggered every time anything is post back.
use this
Private Sub hospitals_Load(sender As Object, e As EventArgs) Handles Me.Load
If Page.IsPostBack Then
//do stuff when post back occurs
Else
Me.PopulateAreas() //put this function here so that it executes only once
End If
End Sub
If your dropdown values have to change on the postback. Say initially the values where 1,2,3,4 and on postback if the values has to be 2,3,4,5 based on some of the values you change on the form controls you will have to clear the dropdown values first and then add new values to it.
areasList.Items.Clear()
Also see that AppendDataBoundItems is not true: in your .aspx page
Change your code to,
Private Sub PopulateAreas()
If IsPostBack Then
areasList.Items.clear()
Dim citySelector As DropDownList = Page.Master.FindControl("locationSelector")
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "Select * from areas where areaCity Like '" + citySelector.SelectedItem.ToString + "%'"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("areaName").ToString()
item.Value = sdr("areaID").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
areasList.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
End If
End Sub
This is my interface, all the asp elements displayed are dynamically created! (Except the header)
Things I perform dynamically:
1. Create row with all those asp elements when page loads or button clicked.
2. I am able to lo populate DropDownList in "Items" column from database when it is created dynamically.
What I want to achieve?:
I want to load 'item code' 'item price' to appropriate text box when the item is selected from the DropDownList.
(Ex: when I click Laptop; it should load its item code and unit price to appropriate text box)
(Sorry for my bad programming approach, I'm beginner to asp.net)
'Page Load function'
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack or Page.IsPostBack Then
GenerateRows(numRows) 'Creates dynamic Table row and column with TextBox and DropDownList'
End If
End Sub
'Dynamic generating function, i have trimmed the code, to make it simple'
Protected Sub GenerateRows(numRows As Integer)
For i = 0 To numRows
Dim tRow As New TableRow
Dim tCode As New TableCell
Dim tItem As New TableCell
Dim lCode As New TextBox
Dim dList As New DropDownList
con = New Data.SqlClient.SqlConnection("Data Source=(localdb)\Projects;Initial Catalog=DataStore;Integrated Security=True")
con.Open()
query = "Select Item_Desc from Product"
cmd = New Data.SqlClient.SqlCommand(query, con)
cmd.ExecuteNonQuery()
dList.DataSource = cmd.ExecuteReader
dList.DataTextField = "Item_Desc"
dList.DataBind()
dList.Items.Insert(0, New ListItem("--- Select Product ---"))
dList.Height = 30
dList.AutoPostBack = True
dList.CausesValidation = True
AddHandler dList.SelectedIndexChanged, AddressOf Dynamic_Method
con.Close()
tCode.Controls.Add(lCode)
tItem.Controls.Add(dList)
tRow.Cells.Add(tCode)
tRow.Cells.Add(tItem)
Table1.Rows.Add(tRow) 'Table1 is not dynamic element'
Next
numRows += 1
ViewState("RowCount") = numRows 'numRows is Global variable'
End Sub
'This function is called when the selected index of DropDownList changes'
Protected Sub Dynamic_Method(ByVal sender As Object, ByVal e As EventArgs)
con = New Data.SqlClient.SqlConnection("Data Source=(localdb)\Projects;Initial Catalog=DataStore;Integrated Security=True")
con.Open()
Dim DDL As DropDownList = DirectCast(sender, DropDownList)
query = "Select * from Product where Item_Desc='" & DDL.SelectedValue.ToString & "'"
cmd = New Data.SqlClient.SqlCommand(query, con)
cmd.ExecuteNonQuery()
dr = cmd.ExecuteReader
If dr.HasRows = True Then
While (dr.Read)
ic = dr(0) 'dr(0) contains Item code of selected value which i need to add to textbox'
End While
End If
con.Close()
End Sub
I'm trying to increment my variable on a button click. It increments only once. It seems as though it's getting lost when it reloads the page.
I'm using the following code:
Dim ItemSelect As New ArrayList()
Dim Quantities As New ArrayList()
Dim itemQtyOrdered As Integer
Public Sub ShtickDataList_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.ListViewCommandEventArgs) Handles ShtickDataList.ItemCommand
If e.CommandName = "ViewCart" Then
Response.Redirect("~/ShoppingCart.aspx")
End If
If e.CommandName = "addToCart" Then
Dim itemQuantity As DropDownList = e.Item.FindControl("QuantityDropDown")
itemQtyOrdered = itemQuantity.SelectedValue
ItemSelect.Add(e.CommandArgument)
Quantities.Add(itemQtyOrdered)
Session("itemInCart") = ItemSelect
Session("quantities") = Quantities
viewInvoice()
End If
End Sub
Protected Sub viewInvoice()
Dim itemSelected As ArrayList = DirectCast(Session("itemInCart"), ArrayList)
Dim QuantityofItem As ArrayList = DirectCast(Session("quantities"), ArrayList)
Dim conn As SqlConnection
Dim comm As SqlCommand
Dim reader As SqlDataReader
Dim purimConnection2 As String = ConfigurationManager.ConnectionStrings("Purim").ConnectionString
conn = New SqlConnection(purimConnection2)
comm = New SqlCommand("SELECT ProductName FROM Products WHERE ProductID = #ProductID", conn)
Dim i As Integer
For i = 0 To ItemSelect.Count - 1
comm.Parameters.Add("#ProductID", Data.SqlDbType.Int)
comm.Parameters("#ProductID").Value = ItemSelect(i)
Next
Try
conn.Open()
reader = comm.ExecuteReader()
ViewCartlink.Text = "View Cart: (" & ItemSelect.Count & ")"
Finally
conn.Close()
End Try
End Sub
Ah, you may be referring to ItemSelect and Quantities lists. You need to look for them in Session and only create them if they are not in the Session. I am rusty on VB.NET, so this is C# version. In Page_Load:
ItemSelect = (ArrayList)Session["itemInCart"];
if (ItemSelect == null)
{
ItemSelect = new ArrayList();
Session["itemInCart"] = ItemSelect;
}
and the same for Quantities.
Also, your loop in viewInvoice method is wrong. For more than one item in ItemSelect list you are adding multiple parameters with the same name. You probably only wanted to do it once with
comm.Parameters("#ProductID").Value = ItemSelect(ItemSelect.Count - 1)
I have two relational tables: the Profiles table which contains 3 kinds of user roles (Manager, Developer, Common User) and the Users table which contains information about the user and their roles ID (Profile_ID field) in the Access 2010 database.
I created a Webform in ASP.NET which should simply register users, asking for their names, selecting their roles in a dropdown list and inserting it all in the Access database. The code populates a grid view with every registred user and a dropdown list with each role on page load:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Start connection
Dim cs As String = ConfigurationManager.ConnectionStrings("Access 2010").ConnectionString
Dim cn As New OleDbConnection(cs)
cn.Open()
'Retrieve User Data
Dim cmd As New OleDbCommand
With cmd
.Connection = cn
.CommandText = "SELECT * FROM Users"
.CommandType = CommandType.Text
End With
Dim ddlValues As OleDbDataReader = cmd.ExecuteReader()
'Populate User Grid View
grdUsers.DataSource = ddlValues
grdUsers.DataBind()
ddlValues.Close()
'Retrieve Profile data
With cmd
.Connection = cn
.CommandText = "SELECT * FROM Profiles"
.CommandType = CommandType.Text
End With
ddlValues = cmd.ExecuteReader()
'Populate Dropdown Profiles
ddRoles.DataSource = ddlValues
ddRoles.DataTextField = "Nome"
ddRoles.DataValueField = "ID"
ddRoles.DataBind()
'Close connections
ddlValues.Close()
cmd.Dispose()
cn.Dispose()
End Sub
Lately it inserts into the database once button clicked:
Protected Sub btnRegister_Click(sender As Object, e As EventArgs) Handles btnRegister.Click
Dim cs As String = ConfigurationManager.ConnectionStrings("Access 2010").ConnectionString
Dim cn As New OleDbConnection(cs)
Dim cmd As New OleDbCommand
With cmd
.CommandText = "INSERT INTO Users (nome, Profile_ID) VALUES ('" & Me.txtNome.Text & "', " & Me.ddRoles.SelectedValue & ")"
.Connection = cn
.Connection.Open()
.ExecuteNonQuery()
.Connection.Close()
.Dispose()
End With
cn.Dispose()
Response.Redirect(Request.Url.AbsoluteUri)
End Sub
The code runs without problems but no matter which item in the dropdown I choose it will always create as Common User (which is the first record in this table). Although I checked the html generated:
<select name="ctl00$MainContent$ddRoles" id="MainContent_ddRoles">
<option value="5">Common User</option>
<option value="6">Developer</option>
<option value="7">Manager</option>
It seems right, but my database only has records with the ID number 5. Can anyone help me?
You're blowing away the selection in the DropDown list by binding on every call to Page_Load. You need to only bind when !IsPostback.