Showing posts with label value. Show all posts
Showing posts with label value. Show all posts

Saturday, March 31, 2012

trim

How do I trim a value that has whitespace after the last character?
ie
<Value>123456 </Value
thanks
markif you merely use Trim(value)
or myVar.Trim
--
this will assure you have no white space at either end
Hi,

TryString.Trim Method

HTH

Trim function in VB.NET

Hey,

In my code the value of strWebService is initially "2 " (that is the number two followed by a space). I then use trim to eliminate the space:


strWebService = readHtmlPage(strTMQuery)
strWebService = Trim(strWebService)

I then run strWebService through a SELECT statement and it always defaults to ELSE:

Select Case strWebService
Case "0"
pnlLogin.Visible = False
pnlPassengerList.Visible = True
Case "1"
lblLoginError.Text = "Password is wrong...<br /><br />"
lblLoginError.Visible = True
Case "2"
lblLoginError.Text = "E-mail address incorrect or not a valid user...<br /><br />"
lblLoginError.Visible = True
Case Else
lblLoginError.Text = "Unknown Error: " & strWebService & "<br /><br />"
lblLoginError.Visible = True
End Select

What am I doing wrong?

MikeHello -

Perhaps you might want to do a conversion to an integer for the case statement?

good luck

take care
tony
I added the following line before my select statement:

Dim intWebService As Integer = CInt(strWebService)

I then removed the double quotes from my case expressions and ran the code but still got the ELSE statement. VB doesn't require BREAK does it?
did you trying doing a response.Write(intWebService) right before the case statement so you can verify the value?


response.write("service =" & strWebService & ".")

Take note of the spaces and period. Should be
service =2.
My code now reads like this (I added the = signs to the label just to make sure the TRIM did its job...)


strWebService = readHtmlPage(strTMQuery)
strWebService = RTrim(strWebService)
Dim intWebService As Integer = CInt(strWebService)

lblTest.Text = "=" & intWebService.ToString & "="
lblTest.Visible = True

Select Case strWebService
Case 0
pnlLogin.Visible = False
pnlPassengerList.Visible = True
Case 1
lblLoginError.Text = "Password is wrong...<br /><br />"
lblLoginError.Visible = True
Case 2
lblLoginError.Text = "E-mail address incorrect or not a valid user...<br /><br />"
lblLoginError.Visible = True
Case Else
lblLoginError.Text = "Unknown Error: " & strWebService & "<br /><br />"
lblLoginError.Visible = True
End Select

I still get the ELSE... Plus, my label does infact read 2... I don't get what I could be doing wrong...
Your select Statement is still referring to strWebService... Change it to intWebService...
Ha ha, good call. It works. Thanks guys. Strings in SELECT CASE statements SUCK!

trim querystring

Is there a way to request the whole querystring after the "?"

I want to pull every name value pair out of the querystring in one string.

Thanks!

mike123You may try "Request.QueryString".
No luck

Anything else ?

Thanks!
mike123
I think Request.ServerVariables("QUERY_STRING") will return what you are after?

Simon

Trimming data in dropdownlist from sqldatareader

When I databind a value/text combination from an
sqldatareader to a dropdownlist, the trailing spaces are
getting included in the dropdownlist. I can RTRIM from
within the SQL to fix this problem, but I am wondering if
there is a more elegant solution to trim all the
text/value combinations in a dropdownlist.Hi William

To my knowledge, there is not an elegant way from dropdownlist side. One
clumsy way I can think of is to populate a new collection or arraylist that
contains the data fields to be bound to the dropwodnlist. While populating
this new collection or arraylist we can trim the data accordingly.

Please let me know if it makes sense.

Best regards,

Jacob Yang
Microsoft Online Partner Support
Get Secure! C www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
Yes, that makes sense. Thank you.
>--Original Message--
>Hi William
>To my knowledge, there is not an elegant way from
dropdownlist side. One
>clumsy way I can think of is to populate a new
collection or arraylist that
>contains the data fields to be bound to the
dropwodnlist. While populating
>this new collection or arraylist we can trim the data
accordingly.
>Please let me know if it makes sense.
>Best regards,
>Jacob Yang
>Microsoft Online Partner Support
>Get Secure! C www.microsoft.com/security
>This posting is provided "as is" with no warranties and
confers no rights.
>.

Wednesday, March 28, 2012

Trouble Declaring and Setting Variable

I have a page that sends the value of a textbox in a form through GET.

My next page is supposed to grab that value, and put it in a variable. This is what I have for my next page:

1<%@dotnet.itags.org. Import namespace="System.IO"%>2<html>
3<head>
4<title>Uploading a File</title>
5678<script language="VB" runat="server">
9Dim strPath
10 strPath = Request.QueryString("path")
11
12 Dim savePath As String = StrPath
13Sub Upload_Click(source As Object, e As EventArgs)
1415 If Not (uploadedFile.PostedFile Is Nothing) Then
16 Try
17 Dim postedFile = uploadedFile.PostedFile
18 Dim filename As String = Path.GetFileName(postedFile.FileName)
19 Dim contentType As String = postedFile.ContentType
20 Dim contentLength As Integer = postedFile.ContentLength
2122 postedFile.SaveAs(savePath & filename)
23 message.Text = postedFile.Filename & " uploaded" & _
24 "<br>content type: " & contentType & _
25 "<br>content length: " & contentLength.ToString()
26 Catch exc As Exception
27 message.Text = "Failed uploading file"
28 End Try
29 End If
30End Sub
31</script>
32
33</head>
34<body>
35
36<form id="Form1" enctype="multipart/form-data" runat="server">
37 Select File to Upload:
3839 <input id="uploadedFile" type="file" runat="server">
40 <p>
41 <input type=button id="upload"
42 value="Upload"
43 OnServerClick="Upload_Click"
44 runat="server">
45 <p>
46 <asp:Label id="message" runat="server"/>
47</form>
48
49</body>
50</html>

I get a "declaration expected" on line 10. Any Ideas why?

A simle fix is to move both lines

Dim strPath as String = Request.QueryString("path")
Dim savePath As String = StrPath

to the top of Sub Upload_Click.


The actual error is that line 9 is not complete with a type declaration.

Dim strPathAs String

Also, you don't seem to need both strPath and savePath.

Dim savePath As String = Request.QueryString("path")
should be enough 


Gunteman, I must respectfully disagree. If you put

Dim savePath As String = Request.QueryString("path")

outside of Sub Upload_Click, you get the following exception:

"Request is not available in this context."

However, removing strPath does make sense.


Thanks to both of you. I still got a problem even after doing that, but adding "Context." before "Request" cleared things up.


louis210:

Gunteman, I must respectfully disagree. If you put

Dim savePath As String = Request.QueryString("path")

outside of Sub Upload_Click, you get the following exception:

"Request is not available in this context."

Quite right!

Monday, March 26, 2012

Trouble formating string for label.

Hey everyone!

Weird situation here. I have this label:

<asp:label id="lblDepositDue" runat="server" />

I am trying to set it's value with this statement:
lblDepositDue.Text = "Deposit Due Upon Booking: " & String.Format("{0:c}", intDepositDue.ToString)

Simple right? But the output still comes out looking like this:

Deposit Due Upon Booking: 4999

...instead of like this which SHOULD be the output:

Deposit Due Upon Booking: $4,999.00

What is going wrong?

Thanks.....MikeHow about something like this:


lblProductCost.Text = Format(intProductCost, "#,##0.00")

Hey...

When I try:

lblDepositDue.Text = "Deposit Due Upon Booking: " & Format(intTotalTourCost.ToString, "#,##0.00")

It comes out like this:

Deposit Due Upon Booking: #,##0.00

:-/
Hi,

as was said, do not call ToString for the integer argument passed to the Format function (it was same problem with your original code):

Instead of:


Format(intTotalTourCost.ToString, "#,##0.00")

use

Format(intTotalTourCost, "#,##0.00")

In your original code following would have worked:


String.Format("{0:c}",intDepositDue)

Note that ToString is not called for the argument. String formatting is formatting from another data type type to string. Capability to format comes when argument is typed, If you pass it as string with ToString method, it's original type is not known (strictly speaking is, it is string as well and goes through formatting as is) and it can't be formatted.
Teemu,

Thank you very much for the clarification. I was under the (incorrect) assumption that String.Format required that the value passed to is was in string format already. I wasn't aware of any conversion to string simply by formatting.

Thanks again!

Mike

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.

Saturday, March 24, 2012

Trouble updating

I have a Access database with 2 text fields. I'm reading one field into a text box, changing the value in the textbox and attempting to update the database with the new value. The page loads fine with the correct value in the textbox, but I'm getting a error on the Update statement. Below is the code. Any suggestions?

Sub LoadInventory()
Connect()
Dim strQuery As String = "SELECT Type, Number FROM Inventory WHERE type = 'squares'"

Dim dbComm As New OLEDBCommand(strQuery, objConnection)
Dim reader As OLEDBDataReader = dbComm.ExecuteReader()

reader.Read()
txtAmount.Text = reader.GetString(1)

reader.Close()
Disconnect()
End Sub

Sub btnChange_Click(ByVal Sender As Object, ByVal E As EventArgs)
UpdateInventory()
LoadInventory()
End Sub

Private Sub UpdateInventory()
Dim strSQL As String = "UPDATE Inventory SET Number = " & txtAmount.Text & " WHERE Type = 'squares'"
Connect()
Dim dbComm As New OLEDBCommand(strSQL, objConnection)
dbComm.ExecuteNonQuery()
Disconnect()
End Subinstead of

Dim strSQL As String = "UPDATE Inventory SET Number = " & txtAmount.Text & " WHERE Type = 'squares'"

try this
Dim strSQL As String = "UPDATE Inventory SET Number = " & Convert.ToInt32(txtAmount.Text) & " WHERE Type = 'squares'"

Jeff
Jeff,

Thanks for your reply. That however didn't work. Could it be the way I have my access database setup?

Jeremy
Jeff,

Does it work when you try putting in a static value for txtAmount.Text such as this:

"UPDATE Inventory SET Number =1 WHERE Type='squares'"

If it does work like that, then try doing this:


Try
Dim dbComm As New OLEDBCommand(strSQL, objConnection)
dbComm.ExecuteNonQuery()
Catch dbException As Exception
Response.Write(dbException.ToString())
End Try

Tell us what the exception is. Besides, it is always good practice anyway to put database queries inside a try statement - there are just way too many things that could go wrong to not catch those errors.

Aaron

Trouble with changing a value in a cookie.

I wanted to change a value in a existing cookie. I read the old value, modify it and to write the new value in the old cookie. Here is the code:

public bool SetCookie(string cookiename, string cookievalue, int iDaysToExpire) //create the cookie
{
try
{
HttpCookie objCookie = new HttpCookie(cookiename);
Response.Cookies.Clear();
Response.Cookies.Add(objCookie);
objCookie.Values.Add(cookiename, cookievalue); // adding the value to the cookie
DateTime dtExpiry = DateTime.Now.AddDays(iDaysToExpire); //expires
Response.Cookies[cookiename].Expires = dtExpiry;
}
catch (Exception e)
{
return false;
}
return true;
}

public string GetCookie(string cookiename)// method which gives the value from the cookie
{
string cookyval = "";
try
{
cookyval = Request.Cookies[cookiename].Value;
}
catch (Exception e)
{
cookyval = "";
}
return cookyval;
}

protected void Page_Load(object sender, EventArgs e)
{

String t, s,t1;
int i = 0;
s = "";
t = "";

t = GetCookie("test");//reading the cookie
//removing the name and getting the value
try
{
lbl1.Text = t; //
t1 = t.Remove(0, 9);
i = Int32.Parse(t1);
i = i + 1; //the value is modified
}
catch (Exception w) { lbl3.Text = "Convert isnt working."; }
s = Convert.ToString(i);

//writing the new value in the cookie
SetCookie("test", s, 1);

//testing to see if the new value is written
t1 = GetCookie("test");
lbl2.Text = s;
lbl3.Text = t1;
}
}What is your question, exactly? This code re-sets the cookie each time it runs. It seems to return exactly what you're setting it to ("test=0"). (Is that the value that you want it to have?)

Thursday, March 22, 2012

Trouble with Request.Form- output is blank

Hey all,

I'm very much new to ASP and ASP.net, and I'm having difficulties in figuring out to get ASP.net to properly output the value of a form field in a vb script. The field in particular is one that contains a two-letter abbreviation of a state (E.g. if the visitor selected California, the value of the field would be CA). This normally works fine, but when a visitor selects Indiana, that's where ASP.net returns nothing. I can see that ASP.net recognizes IN as VB code, I'm just not sure how to force it to just print IN.

Here's a snippet of the code:


obj.OrigZipPostal = Request.Form("vendorpostal" & i)
obj.OrigStateProvince = Request.Form("vendorstate" & i)

Thanks for helping a newbie out :D

You need to convince vb.net that you are using a string and not a command, you could try CStr() or use quotes...

Hope that this helps.


Use

obj.OrigStateProvince = CStr(Request.Form("vendorstate" & i))

Thanks


Thanks guys, that solved the problem.

Tuesday, March 13, 2012

Troubles displaying a changing read-only value

I am writing a form with one value being a total of a couple other values from my page. I put this in a read-only textbox so it can't be changed, and when I change the other boxes values, the JavaScript automatically changes this value. However, when I generate the e-mail I use textboxTotalSpace.text to make it appear in my email, but this will only display the original value, and not the new one.

Does anyone know how I fix this?

Thanks.

TextBox server control will not pick up the changed values (during LoadPostData()) if the textbox is set to read only. Check this link for a fix:

http://aspadvice.com/blogs/joteke/archive/2006/04/12/16409.aspx

Hope this helps,

Vivek


Thanks Vivek, but I am unsure where I am supposed to add theTextBox1.Attributes.Add("readonly","readonly")


That should go in the Page_Load event.

protected void Page_Load(object sender, EventArgs e)
{
// add the javascript attributes
TextBox1.Attributes.Add("readonly", "readonly");
}

Thanks


Because you are changing data at client side using java script....


You can put this in the Page Load method.


suresh modiya:

Because you are changing data at client side using java script....

Changed text box value client side WILL show up in the server code behind because textbox implements IPostBackDataHandler interface and it loads its value from the forms POST data in the LoadPostBackData() method.

Its only when it is set to readonly that this data load will not work on postback, hence the alternative.

Vivek

Troubles with DropDownList

Hi

I've got problem with DropDownList, because when I change values, I've still got the first value of List.

So, how to set new selected value of DropDownList?I guess you have the following code concept in your page: "on a page_load, retrieve the data from a database or some other source and bind it to the control". This is right but incomplete. In fact Page_Load is fired also on a postback, so when a user selects something in the dropdownlist and the page is posted back (automatically or manually) to the server, the Page_Load is executed again. In order to execute the binding code only when needed, use this skeleton of code:

if (!Page.IsPostBack) {
//do the binding
}
//do other things that are not affected by a postback
.

Now, you're rebinding the controls every time the page is loaded; this code will perform the binding only when no postback is done (thus, only on the first request to the page).
Great Thanks
Now everything is working :)