Monday, March 26, 2012

Trouble getting dropdownlist value

Using asp.net, I have a form with a dropdownlist that is populated onload. I do this by binding to a datareapter. My first question is how can I add value and text to the dropdown with binding. I see you can do this by ListItem.Value but is there an easy solution?

My other issue is that my value that comes back is always the first item in my list?

Need some help.

<%@dotnet.itags.org. Page Language="VB" ContentType="text/html" ResponseEncoding="iso-8859-1" Trace="false" debug="true"%>
<%@dotnet.itags.org. import Namespace="System.Data.SqlClient" %>
<%@dotnet.itags.org. Import Namespace="System.Data" %>
<%@dotnet.itags.org. Import Namespace="System.IO" %>

<script runat="server">

Sub Add_Info(s As Object, e as EventArgs)
lblMsg.Text = drpManufacturer.SelectedValue
End Sub

Sub Page_Load

Dim conPubs as SqlConnection
Dim cmdSQL as SqlCommand
Dim dtrAllProducts as SqlDataReader

'Retrieve records from database
conPubs = New SqlConnection("Server=xx.xx.xx.xx;uid=name;pwd=pwd;database=db")
cmdSQL = New SqlCommand("SELECT * FROM why3s_products", conPubs)
conPubs.Open()
dtrAllProducts = cmdSQL.ExecuteReader()

'Bind to Repeater
rptPrdList.DataSource = dtrAllProducts
rptPrdList.DataBind()

dtrAllProducts.Close()
conPubs.Close()

'Retrieve records from database
conPubs = New SqlConnection("Server=xx.xx.xx.xx;uid=name;pwd=pwd;database=db")
cmdSQL = New SqlCommand("SELECT manufacturers_name FROM why3s_manufacturers", conPubs)
conPubs.Open()
dtrAllProducts = cmdSQL.ExecuteReader()

'Bind to DropDownList
drpManufacturer.DataSource = dtrAllProducts
drpManufacturer.DataTextField = "manufacturers_name"
drpManufacturer.DataBind()

dtrAllProducts.Close()
conPubs.Close()
End Sub

</script>
<html>
<head>
<title>Add New Manufacturer</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<form id="frmAdd" name="frmAdd" action="addproduct.aspx" method="post" enctype="multipart/form-data" runat="server">
<!--#include file="inc_top_menu.aspx" --><br>

<table cellspacing="0" cellpadding="0" width="750" border="0">
<tbody>
<tr>

<td width="125" valign="top"> <asp:validationsummary ID="ValidationSummary1" runat="server" ShowMessageBox="True" HeaderText="Missing:" DisplayMode="List"></asp:validationsummary>
</td>
<td width="625">
<table cellspacing="2" cellpadding="0" width="100%" border="0">
<tbody>
<tr>
<td>Manufacturer:</td>
<td><asp:dropdownlist ID="drpManufacturer" runat="server"></asp:dropdownlist>
- <em><font size="2" face="Verdana, Arial, Helvetica, sans-serif">If
not in list please create before you continue.</font></em></td>
</tr>
<tr>
<td width="26%"> Product Model Name:</td>
<td width="74%"> <asp:textbox id="txtModel" runat="server" TextMode="SingleLine" MaxLength="15"></asp:textbox> <asp:requiredfieldvalidator id="RequiredFieldValidator1" runat="server" Text="Required" ErrorMessage="Model Name" ControlToValidate="txtModel"></asp:requiredfieldvalidator> </td>
</tr>
<tr>
<td>Product Fullmodel Name:</td>
<td><asp:textbox AutoPostBack="false" ID="txtFullModel" MaxLength="60" runat="server" /> <asp:requiredfieldvalidator ControlToValidate="txtFullModel" ErrorMessage="Fullmodel Name" Text="Required" runat="server" /> </td>
</tr>
<tr>
<td> Product Image:</td>
<td><input name="inpFileUpload" type="file" id="inpFileUpload" size="40" maxlength="60" Runat="Server">
<font size="1" face="Verdana, Arial, Helvetica, sans-serif"><em>300kb
max file size.</em></font></td>
</tr>
<tr>
<td> Product Description</td>
<td> <asp:textbox id="txtDescription" runat="server" TextMode="SingleLine" MaxLength="255" Columns="50"></asp:textbox> <asp:requiredfieldvalidator id="RequiredFieldValidator2" runat="server" Text="Required" ErrorMessage="Description" ControlToValidate="txtDescription"></asp:requiredfieldvalidator> </td>
</tr>
<tr>
<td>Product Price:</td>
<td><asp:textbox ID="txtPrice" MaxLength="10" runat="server" /> <asp:requiredfieldvalidator ControlToValidate="txtPrice" ErrorMessage="Price" InitialValue="Required" runat="server" Text="Required" /> </td>
</tr>
<tr>
<td>Product Retail Price:</td>
<td><asp:textbox ID="txtRetail" MaxLength="10" runat="server" /></td>
</tr>
<tr>
<td>Product Cost:</td>
<td><asp:textbox ID="txtCost" MaxLength="10" runat="server" /></td>
</tr>
<tr>
<td>Product Wholesale Price:</td>
<td><asp:textbox ID="txtWholesale" MaxLength="10" runat="server" /></td>
</tr>
<tr>
<td>Product Weight:</td>
<td><asp:textbox ID="txtWeight" MaxLength="7" runat="server" /></td>
</tr>
<tr>
<td>Product Status:</td>
<td><div align="left">
<asp:dropdownlist ID="drpStatus" runat="server">
<asp:listitem Text="Show" runat="server"></asp:listitem>
<asp:listitem Text="Hide" runat="server"></asp:listitem>
</asp:dropdownlist>
<em><font size="1" face="Verdana, Arial, Helvetica, sans-serif">Display
vacuum on page.</font></em></div></td>
</tr>
<tr>
<td>Product Sold-To-Dt:</td>
<td><asp:textbox ID="txtSTD" MaxLength="4" runat="server" Text="0" /> <asp:requiredfieldvalidator ControlToValidate="txtSTD" ErrorMessage="Sold-To-Date" InitialValue="Required" Text="Required" runat="server" /> </td>
</tr>
<tr>
<td>Product Show Button:</td>
<td><asp:dropdownlist ID="drpShowBuy" runat="server">
<asp:listitem Text="Show" runat="server"></asp:listitem>
<asp:listitem Text="Hide" runat="server"></asp:listitem>
</asp:dropdownlist> <em><font size="1" face="Verdana, Arial, Helvetica, sans-serif">Do
not display the buy button.</font></em></td>
</tr>
<tr>
<td>Product Special Notify:</td>
<td><asp:textbox ID="txtSpecialNotify" MaxLength="55" runat="server" /></td>
</tr>
<tr>
<td>Product Quantity:</td>
<td><asp:textbox ID="txtQuantity" MaxLength="4" runat="server" Text="0" /></td>
</tr>
<tr>
<td> </td>
<td><asp:button ID="butAdd" OnClick="Add_Info" runat="server" Text="Add" BackColor="Yellow" BorderColor="Blue" BorderStyle="Groove"></asp:button> <asp:label ID="lblError" runat="server"></asp:label></td>
</tr>
<tr>
<td> </td>
<td><asp:label ID="lblMsg" runat="server"></asp:label></td>
</tr>

</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</form>
<br />
<center>
<asp:repeater EnableViewState="false" ID="rptPrdList" runat="server">
<headertemplate>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Image</th>
<th>Entry_Dt</th>
<th>Description</th>
</tr>
</headertemplate>

<itemtemplate>
<tr bgcolor="#CCFFFF">

<td><a href="http://links.10026.com/?link=updatemanufacturer.aspx?ID=<%# Container.DataItem("manufacturers_id") %>"><%# Container.DataItem("manufacturers_id") %></a></td>
<td><%# Container.DataItem("manufacturers_name") %></td>
<td><%# Container.DataItem("manufacturers_image") %></td>
<td><%# Container.DataItem("manufacturers_entry_dt") %></td>
<td><%# Container.DataItem("manufacturers_description") %></td>
</tr>
</itemtemplate>

<AlternatingItemTemplate>
<tr bgcolor="#99FF66">
<td><%# Container.DataItem("manufacturers_id") %></td>
<td><%# Container.DataItem("manufacturers_name") %></td>
<td><%# Container.DataItem("manufacturers_image") %></td>
<td><%# Container.DataItem("manufacturers_entry_dt") %></td>
<td><%# Container.DataItem("manufacturers_description") %></td>
</tr>
</AlternatingItemTemplate>

<footertemplate>
</table>
</footertemplate>
</asp:repeater>
</center>
</body>
</html>1)
Set the DataTextField for the text to display.
Set the DataValueField for the value for that text.

2) You need to check of the PostBack

If Not Page.IsPostBack
'Do this code if the page isn't posted back
End If

3) Why are you creating 2 connections in the Page_Load event?
Try something like this

Sub Page_Load

Dim conPubs as SqlConnection
Dim cmdProducts as SqlCommand
Dim cmdManufacturers as SqlCommand
Dim dtrAllProducts as SqlDataReader
Dim dtrAllManufacturers As SqlDataReader

'Retrieve records from database
conPubs = New SqlConnection("Server=xx.xx.xx.xx;uid=name;pwd=pwd;database=db")

cmdProducts = New SqlCommand("SELECT * FROM why3s_products", conPubs)
cmdManufacturers = New SqlCommand("SELECT manufacturers_name FROM why3s_manufacturers", conPubs)

Try
conPubs.Open()
dtrAllProducts = cmdProducts.ExecuteReader()
dtrAllManufacturers = cmdManufacturers.ExecuteReader()

'Bind to Products to Repeater
rptPrdList.DataSource = dtrAllProducts
rptPrdList.DataBind()

'Bind to DropDownList
drpManufacturer.DataSource = dtrAllManufacturers
drpManufacturer.DataTextField = "manufacturers_name"
drpManufacturer.DataValueField = "manufacturers_ID"
drpManufacturer.DataBind()

dtrAllProducts.Close()
dtrManufacturers.Close()

conPubs.Close()

Catch ex As Exception
Response.write("Error Occurred: " & ex.Message & "<br>" & ex.StackTrace)
End Try

End Sub
Thanks for the quick response.

I changed to 1 connection but get the following at the top of my page:

Error Occurred: There is already an open DataReader associated with this Connection which must be closed first. .....

This points to the following line:
dtrAllManufacturers = cmdManufacturers.ExecuteReader()

Setting the DataValueField does make sense now.

I am very new to asp.net. Is the Try, Catch ex As Exception the new On Error?

Thanks again for your help.
okay, open the first reader, process the data, close the reader, then do the same with the second reader.
Yes, this does work.

My other issue is I can't get the value selected to return.

Is it due to the IsPostBack? I have this in a On_Click event so does the Page_Load reset my selection?

<%@. Page Language="VB" ContentType="text/html" ResponseEncoding="iso-8859-1" Trace="false" debug="true"%>
<%@. import Namespace="System.Data.SqlClient" %>
<%@. Import Namespace="System.Data" %>
<%@. Import Namespace="System.IO" %>

<script runat="server">

Sub Add_Info(s As Object, e as EventArgs)
If IsValid Then
'Query db to see if product is found if not then insert new record.
Dim conPubs as SqlConnection
Dim sSQL as SqlCommand
Dim sTmpSQL as String
Dim sInsertSQL as String
Dim cmdInsertSQL as SqlCommand
Dim dtrUsers as SqlDataReader
Dim iFoundPrds as Integer
Dim iInsertCnt as Integer
Dim sFileName as String
Dim sFullImagePath as String
Dim sFolder as String
Dim sImageSize as String

'Get the name of the file posted
sFileName = inpFileUpload.PostedFile.Filename
'In bytes 29.9 KB (30,704 bytes)
'Don't want to allow more then 307,200 bytes
sImageSize = inpFileUpload.PostedFile.ContentLength
sFileName = Path.GetFileName(sFileName) sFolder = "C:\websites\dir1\dir2\site.com\images\"

'Determine if an image is sent.
If Len(sFileName) > 0 Then
If sImageSize <= 307200 Then
sFullImagePath = "images\" & sFileName
End if
End if

'Create the directory if it does not exist
If (not Directory.Exists(sFolder)) Then
Directory.CreateDirectory(sFolder)
End if

iInsertCnt = 0
conPubs = New SqlConnection("Server=xx.xx.xx.xx;uid=name;pwd=pwd;database=dbname")
conPubs.Open()
sTmpSQL = "SELECT count(*) as ProductsFound FROM why3s_products where UPPER(RTRIM(products_model)) = '" & UCase(txtModel.Text) & "' AND manufacturers_id = 1"
lblMsg.Text = sTmpSQL
sSQL = New SqlCommand(sTmpSQL, conPubs)
dtrUsers = sSQL.ExecuteReader()
While dtrUsers.Read()
iFoundPrds = dtrUsers("ProductsFound")
End While
dtrUsers.Close()
If iFoundPrds = 0 Then
'lblError.Text = "No users found"
sInsertSQL = "INSERT INTO why3s_products (products_quantity, products_model, products_fullmodel, products_image, products_price, products_retail_price, products_cost, products_wholesale_price, products_entry_dt, products_last_change_dt, products_weight, products_status, products_sold_to_dt, products_description, products_show_buy, products_special_notify, manufacturers_id) values (" & txtQuantity.Text & ", '" & txtModel.Text & "', '" & txtFullModel.Text & "', '" & sFullImagePath & "', " & txtPrice.Text & ", " & txtRetail.Text & ", " & txtCost.Text & ", " & txtWholesale.Text & ", getdate(), getdate(), " & txtWeight.Text & ", 0, " & txtSTD.Text & ", '" & txtDescription.Text & "', 1, '" & txtSpecialNotify.Text & "', 1)"
cmdInsertSQL = New SqlCommand(sInsertSQL, conPubs)
iInsertCnt = cmdInsertSQL.ExecuteNonQuery()
'lblMsg.Text = "You have inserted " & iInsertCnt & " records."

If Len(sFileName) > 0 Then
'Check to see if file already exists
If File.Exists(sFolder & sFileName)
'Only save if file is less then 300kb
If sImageSize <= 307200 Then
'Save file to server
inpFileUpload.PostedFile.SaveAs(sFolder & sFileName)
End if
End if
End if
Else
'lblError.Text = iFoundUsers & " users found."
'lblMsg.Text = "User already found. Please try again."
End iF
conPubs.Close()
'If iInsertCnt > 0 Then
'Response.Redirect("addproduct.aspx")
'End if
Else
'lblError.Text = "Not IsValid"
lblMsg.Text = vbNullString
End if
End Sub

Sub Page_Load

Dim conPubs as SqlConnection
Dim cmdProducts as SqlCommand
Dim cmdManufacturers as SqlCommand
Dim dtrAllProducts as SqlDataReader
Dim dtrAllManufacturers as SqlDataReader

'Retrieve records from database
conPubs = New SqlConnection("Server=xx.xx.xx.xx;uid=name;pwd=pwd;database=dbname")
cmdProducts = New SqlCommand("SELECT * FROM why3s_products", conPubs)
cmdManufacturers = New SqlCommand("SELECT manufacturers_name, manufacturers_id FROM why3s_manufacturers", conPubs)

'Try
conPubs.Open()

dtrAllProducts = cmdProducts.ExecuteReader()

'Bind Manufacturer to Repeater
rptPrdList.DataSource = dtrAllProducts
rptPrdList.DataBind()
dtrAllProducts.Close()

dtrAllManufacturers = cmdManufacturers.ExecuteReader()

'Bind to DropDownList
drpManufacturer.DataSource = dtrAllManufacturers
drpManufacturer.DataTextField = "manufacturers_name"
drpManufacturer.DataValueField = "manufacturers_id"
drpManufacturer.DataBind()

dtrAllManufacturers.Close()

conPubs.Close()

'Catch ex As Exception
'Response.Write("Error Occurred: " & ex.Message & "<br>" & ex.StackTrace)
'End Try
End Sub

</script>
<html>
<head>
<title>Add New Manufacturer</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<form id="frmAdd" name="frmAdd" action="addproduct.aspx" method="post" enctype="multipart/form-data" runat="server">
<!--#include file="inc_top_menu.aspx" --><br>

<table cellspacing="0" cellpadding="0" width="750" border="0">
<tbody>
<tr>

<td width="125" valign="top"> <asp:validationsummary ID="ValidationSummary1" runat="server" ShowMessageBox="True" HeaderText="Missing:" DisplayMode="List"></asp:validationsummary>
</td>
<td width="625">
<table cellspacing="2" cellpadding="0" width="100%" border="0">
<tbody>
<tr>
<td>Manufacturer:</td>
<td><asp:dropdownlist ID="drpManufacturer" runat="server"></asp:dropdownlist>
- <em><font size="2" face="Verdana, Arial, Helvetica, sans-serif">If
not in list please create before you continue.</font></em></td>
</tr>
<tr>
<td width="26%"> Product Model Name:</td>
<td width="74%"> <asp:textbox id="txtModel" runat="server" TextMode="SingleLine" MaxLength="15"></asp:textbox> <asp:requiredfieldvalidator id="RequiredFieldValidator1" runat="server" Text="Required" ErrorMessage="Model Name" ControlToValidate="txtModel"></asp:requiredfieldvalidator> </td>
</tr>
<tr>
<td>Product Fullmodel Name:</td>
<td><asp:textbox AutoPostBack="false" ID="txtFullModel" MaxLength="60" runat="server" /> <asp:requiredfieldvalidator ControlToValidate="txtFullModel" ErrorMessage="Fullmodel Name" Text="Required" runat="server" /> </td>
</tr>
<tr>
<td> Product Image:</td>
<td><input name="inpFileUpload" type="file" id="inpFileUpload" size="40" maxlength="60" Runat="Server">
<font size="1" face="Verdana, Arial, Helvetica, sans-serif"><em>300kb
max file size.</em></font></td>
</tr>
'..... REMOVE CODE TO SHORTEN

<tr>
<td> </td>
<td><asp:button ID="butAdd" OnClick="Add_Info" runat="server" Text="Add" BackColor="Yellow" BorderColor="Blue" BorderStyle="Groove"></asp:button> <asp:label ID="lblError" runat="server"></asp:label></td>
</tr>
<tr>
<td> </td>
<td><asp:label ID="lblMsg" runat="server"></asp:label></td>
</tr>

</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</form>
<br />
<center>
<asp:repeater EnableViewState="false" ID="rptPrdList" runat="server">
<headertemplate>
<table border="1">
<tr>
<th>ID</th>
<th>Model</th>
<th>Manufacturers ID</th>
</tr>
</headertemplate>

<itemtemplate>
<tr bgcolor="#CCFFFF">
<td><a href="http://links.10026.com/?link=updateproduct.aspx?ID=<%# Container.DataItem("products_id") %>"><%# Container.DataItem("products_id") %></a></td>
'REMOVED CODE TO FIT
<td><%# Container.DataItem("manufacturers_id") %></td>
</tr>
</itemtemplate>

<AlternatingItemTemplate>
<tr bgcolor="#99FF66">
<td><a href="http://links.10026.com/?link=updateproduct.aspx?ID=<%# Container.DataItem("products_id") %>"><%# Container.DataItem("products_id") %></a></td>
'REMOVED CODE TO FIT
<td><%# Container.DataItem("products_model") %></td>
<td><%# Container.DataItem("manufacturers_id") %></td> </tr>
</AlternatingItemTemplate>

<footertemplate>
</table>
</footertemplate>
</asp:repeater>
</center>
</body>
</html>
Where are you trying to retrieve it at?

Dim ManufacturerID As Integer

ManufacturerID = drpManufacturer.SelectedValue
Well, I did find out that it only works if I do a 'Not IsPostBack' on my On_Load. It must be reloading the form then doing the Button On_CLick.

Is it possible to run my on_click code then refresh the page?

This doesn't really relate to this subject but you seem to have an extremely good handle on .net. When working with forms do you have a function after a users clicks and submits your data that resets the form to the original state or is there code that does this for you?

Thanks again for all your help.
You could set the "EnableViewState" property to "False" on all the controls that have that property.

0 comments:

Post a Comment