Showing posts with label form. Show all posts
Showing posts with label form. Show all posts

Saturday, March 31, 2012

Trim URL

Hi,
I am involved in designing a website in which on a certain page(that contains a form) if some message is to be shown to the user the URL looks like
http://myserver/somepage.aspx?message=.....
Now if on that page the user requests re-submits the form I want the URL to be trimmed as simply http://myserver/somepage.aspx

Also is there some way that I can send such error messages through some means(like POST) such that there is no change in the url.If yes plz elaborate on it

Cheers,
-Aayush

Why don't you pass the parameter into a session, so instead of passing ?message=.....

do

Session["message"] = "...";

and in the next page you do:

string message = Session["message"].ToString();

Session.Remove("message");


you can use server variables and retrieve the required info

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!

Trouble Deploying ASP.NET Application

Hi,

I'm new to ASP.NET and just finished up a small application.
Essentially it's just a form that writes data to a CSV file on the
server after a user fills in the form. The code compiles and runs on
my development machine (VS.NET 2002) but when I FTP all the files to
the server I get a "Server Error in '/' Application." error. I can't
figure out why it won't run. A couple notes:

~ I have no idea of the server settings. It's a clients machine and I
was only told it is a .NET machine.

~ I can't seem to change the Cusomt Error Message in web.config even
though I change the XML, recompile the code and FTP it to the server.

~ This code is residing in a sub-directory of the main web application.

~ I've tried deleteing web.config and Global.asax to see if that would
help but no luck.

Any help would be appreciated,

Justin@dotnet.itags.org.Cutroni.ComMan, you are in a true pickle, Justin.

Let me venture a guess. Under your circumstances, about the only thing you
could do would be a trace IN the page, which you might try, but I sure
wouldn't like to have all the constraints on me that you have, especially if
I was new to .Net!

You say it writes to a file. Therefore, the account under which it is
running must have permission to write to the folder in which the file
resides. My guess would be that it is running under an underpriveleged
account, but you will need to find this out somehow.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Sometimes you eat the elephant.
Sometimes the elephant eats you.

"fenway" <justin.cutroni@.gmail.com> wrote in message
news:1116593037.316248.68600@.g49g2000cwa.googlegro ups.com...
> Hi,
> I'm new to ASP.NET and just finished up a small application.
> Essentially it's just a form that writes data to a CSV file on the
> server after a user fills in the form. The code compiles and runs on
> my development machine (VS.NET 2002) but when I FTP all the files to
> the server I get a "Server Error in '/' Application." error. I can't
> figure out why it won't run. A couple notes:
> ~ I have no idea of the server settings. It's a clients machine and I
> was only told it is a .NET machine.
> ~ I can't seem to change the Cusomt Error Message in web.config even
> though I change the XML, recompile the code and FTP it to the server.
> ~ This code is residing in a sub-directory of the main web application.
> ~ I've tried deleteing web.config and Global.asax to see if that would
> help but no luck.
> Any help would be appreciated,
> Justin@.Cutroni.Com
Hi Kevin,

Thanks for your response. I'm in the process of stepping throught the
file line by line trying to find what's throwing the error.

I agree, it may be a permissions issue with the CSV file.
Unfortunately getting ahold of the sys admin is a time consuimg process
and the only access I have to the server is FTP access.

Justin
So I've been trying to debug a bit and I've found something
interesting. I added a blank ASPX page to my project. This file has
absolutely nothing in it excep a Response.write() call. But if I
compile the project, FTP it to the server and then try to load this
ASPX page I still get the generic "Server Error in '/' Application".

Any thoughts? I could really use a hand.

Thanks,

Justin
Is there anyone out there that can offer a little help re: this issue?
I have a small web app that compiles and runs on my machine but will
not run on the server after I FTP it to the server. Even the simplest
pages throw a "Server Error in '/' Application." error.

I've tried tweking web.config to display a more robust error but that
is not working.
First, if it is in a subdirectory off the main application you must make the
sub-directory it's own application. Otherwise the files in the bin directory
aren't paid attention to since they aren't in the bin directory for the main
application. To make a directory into an applicaton you open the IIS MMC and
select the properties for the particular directory and on the Directory tab
click the button that says Create Application.

Hope this helps,
Mark Fitzpatrick
Microsoft MVP - FrontPage

"fenway" <justin.cutroni@.gmail.com> wrote in message
news:1116593037.316248.68600@.g49g2000cwa.googlegro ups.com...
> Hi,
> I'm new to ASP.NET and just finished up a small application.
> Essentially it's just a form that writes data to a CSV file on the
> server after a user fills in the form. The code compiles and runs on
> my development machine (VS.NET 2002) but when I FTP all the files to
> the server I get a "Server Error in '/' Application." error. I can't
> figure out why it won't run. A couple notes:
> ~ I have no idea of the server settings. It's a clients machine and I
> was only told it is a .NET machine.
> ~ I can't seem to change the Cusomt Error Message in web.config even
> though I change the XML, recompile the code and FTP it to the server.
> ~ This code is residing in a sub-directory of the main web application.
> ~ I've tried deleteing web.config and Global.asax to see if that would
> help but no luck.
> Any help would be appreciated,
> Justin@.Cutroni.Com
THANK YOU!!!! Once I get ahold of the sys admin that's what I'll tell
him to do. I had read some similar things but was unsure if I needed
to make this sub-directory it's own application. Now I know the
answer. Hopefully that works.

Question, is there a way to create ASP.NET code that plugs into the
existing application without having to modify any settings in IIS? It
would be great if I could just drop this code on the server and have it
run "inside" the current application.

Thanks,

justin
re:
> Now I know the answer. Hopefully that works.

Shouldn't you test that it works BEFORE saying that you know the answer ?

re:
> It would be great if I could just drop this code on the server
> and have it run "inside" the current application.

As long as you drop the code in a subdirectory of your
application's directory, everything should work fine.

Juan T. Llibre
ASP.NET MVP
http://asp.net.do/foros/
Foros de ASP.NET en Espaol
Ven, y hablemos de ASP.NET...
======================

"fenway" <justin.cutroni@.gmail.com> wrote in message
news:1116605577.929924.293220@.g14g2000cwa.googlegr oups.com...
> THANK YOU!!!! Once I get ahold of the sys admin that's what I'll tell
> him to do. I had read some similar things but was unsure if I needed
> to make this sub-directory it's own application. Now I know the
> answer. Hopefully that works.
> Question, is there a way to create ASP.NET code that plugs into the
> existing application without having to modify any settings in IIS? It
> would be great if I could just drop this code on the server and have it
> run "inside" the current application.
> Thanks,
> justin
True, I should test it before stating that it works.

So, If I'm reading your note correctly, I should be able to drop my
application in a sub-folder of an existing application and it should
run correctly? I tried that and got an error. Plus I tried to change
web.config to display a more verbose error message but it's still
display the friendly error message.
re:
> I should be able to drop my application in a sub-folder of an
> existing application and it should run correctly?

That's not what you asked.

You asked if you could drop *code* in a sub-folder
of an existing, and whether it would run correctly.

It *will* run correctly, if you drop it as *code*.

What you are attempting to do is *nest* applications, which since
ASP 1.0 has been *verboten* ( forbidden ), because it leads to
*kaput*, i.e., the end of your application.

If you want a different application, create a different application.

If you want a sub-application, just run it in a sub-directory of your main application.
You don't have to run a sub-application as a *different* application.

If you do, that application won't be able
to share any values with your main application

Juan T. Llibre
ASP.NET MVP
http://asp.net.do/foros/
Foros de ASP.NET en Espaol
Ven, y hablemos de ASP.NET...
======================

"fenway" <justin.cutroni@.gmail.com> wrote in message
news:1116606296.822178.125240@.z14g2000cwz.googlegr oups.com...
> True, I should test it before stating that it works.
> So, If I'm reading your note correctly, I should be able to drop my
> application in a sub-folder of an existing application and it should
> run correctly? I tried that and got an error. Plus I tried to change
> web.config to display a more verbose error message but it's still
> display the friendly error message.
One thing to note is that if you use VS.NET to create a ASP.NET web
application its forcing your project to become a virtual directory and it
treats is as 1 appliation. Now if you are uploading a folder to a already
working web app then you gotta check few things:

1. The .dll that VS.NET creates cannot be in the bin folder subdirectory
that you are uploading. The .dll file should be placed in the root directory
of your already working website. You can only place the .dll in the bin
folder within a sub directory if that directory is a virtual directory.

2. VS.NET creates a web.config file with standard elements that you would
find in a asp.net app defined as a virtual directory. Please be mindful that
there are certain elements that can only be declared at the machine level or
at the virtual level and NOT at the subdirectory level. So, check your
web.config file that vs.net creates for you and make sure elements like
<session>, <authentication>, I think thats it, are removed from the
web.config file since they can only be declared for a folder that is a
virtual directory..which your directory is not.

See if any of these helps. This is something I have to go through with
Virtual Hosting companies all the time.

"fenway" wrote:

> Is there anyone out there that can offer a little help re: this issue?
> I have a small web app that compiles and runs on my machine but will
> not run on the server after I FTP it to the server. Even the simplest
> pages throw a "Server Error in '/' Application." error.
> I've tried tweking web.config to display a more robust error but that
> is not working.
>

Trouble Deploying ASP.NET Application

Hi,
I'm new to ASP.NET and just finished up a small application.
Essentially it's just a form that writes data to a CSV file on the
server after a user fills in the form. The code compiles and runs on
my development machine (VS.NET 2002) but when I FTP all the files to
the server I get a "Server Error in '/' Application." error. I can't
figure out why it won't run. A couple notes:
~ I have no idea of the server settings. It's a clients machine and I
was only told it is a .NET machine.
~ I can't seem to change the Cusomt Error Message in web.config even
though I change the XML, recompile the code and FTP it to the server.
~ This code is residing in a sub-directory of the main web application.
~ I've tried deleteing web.config and Global.asax to see if that would
help but no luck.
Any help would be appreciated,
Justin@dotnet.itags.org.Cutroni.ComMan, you are in a true pickle, Justin.
Let me venture a guess. Under your circumstances, about the only thing you
could do would be a trace IN the page, which you might try, but I sure
wouldn't like to have all the constraints on me that you have, especially if
I was new to .Net!
You say it writes to a file. Therefore, the account under which it is
running must have permission to write to the folder in which the file
resides. My guess would be that it is running under an underpriveleged
account, but you will need to find this out somehow.
HTH,
Kevin Spencer
Microsoft MVP
.Net Developer
Sometimes you eat the elephant.
Sometimes the elephant eats you.
"fenway" <justin.cutroni@.gmail.com> wrote in message
news:1116593037.316248.68600@.g49g2000cwa.googlegroups.com...
> Hi,
> I'm new to ASP.NET and just finished up a small application.
> Essentially it's just a form that writes data to a CSV file on the
> server after a user fills in the form. The code compiles and runs on
> my development machine (VS.NET 2002) but when I FTP all the files to
> the server I get a "Server Error in '/' Application." error. I can't
> figure out why it won't run. A couple notes:
> ~ I have no idea of the server settings. It's a clients machine and I
> was only told it is a .NET machine.
> ~ I can't seem to change the Cusomt Error Message in web.config even
> though I change the XML, recompile the code and FTP it to the server.
> ~ This code is residing in a sub-directory of the main web application.
> ~ I've tried deleteing web.config and Global.asax to see if that would
> help but no luck.
> Any help would be appreciated,
> Justin@.Cutroni.Com
>
Hi Kevin,
Thanks for your response. I'm in the process of stepping throught the
file line by line trying to find what's throwing the error.
I agree, it may be a permissions issue with the CSV file.
Unfortunately getting ahold of the sys admin is a time consuimg process
and the only access I have to the server is FTP access.
Justin
So I've been trying to debug a bit and I've found something
interesting. I added a blank ASPX page to my project. This file has
absolutely nothing in it excep a Response.write() call. But if I
compile the project, FTP it to the server and then try to load this
ASPX page I still get the generic "Server Error in '/' Application".
Any thoughts? I could really use a hand.
Thanks,
Justin
Is there anyone out there that can offer a little help re: this issue?
I have a small web app that compiles and runs on my machine but will
not run on the server after I FTP it to the server. Even the simplest
pages throw a "Server Error in '/' Application." error.
I've tried tweking web.config to display a more robust error but that
is not working.
First, if it is in a subdirectory off the main application you must make the
sub-directory it's own application. Otherwise the files in the bin directory
aren't paid attention to since they aren't in the bin directory for the main
application. To make a directory into an applicaton you open the IIS MMC and
select the properties for the particular directory and on the Directory tab
click the button that says Create Application.
Hope this helps,
Mark Fitzpatrick
Microsoft MVP - FrontPage
"fenway" <justin.cutroni@.gmail.com> wrote in message
news:1116593037.316248.68600@.g49g2000cwa.googlegroups.com...
> Hi,
> I'm new to ASP.NET and just finished up a small application.
> Essentially it's just a form that writes data to a CSV file on the
> server after a user fills in the form. The code compiles and runs on
> my development machine (VS.NET 2002) but when I FTP all the files to
> the server I get a "Server Error in '/' Application." error. I can't
> figure out why it won't run. A couple notes:
> ~ I have no idea of the server settings. It's a clients machine and I
> was only told it is a .NET machine.
> ~ I can't seem to change the Cusomt Error Message in web.config even
> though I change the XML, recompile the code and FTP it to the server.
> ~ This code is residing in a sub-directory of the main web application.
> ~ I've tried deleteing web.config and Global.asax to see if that would
> help but no luck.
> Any help would be appreciated,
> Justin@.Cutroni.Com
>
THANK YOU!!!! Once I get ahold of the sys admin that's what I'll tell
him to do. I had read some similar things but was unsure if I needed
to make this sub-directory it's own application. Now I know the
answer. Hopefully that works.
Question, is there a way to create ASP.NET code that plugs into the
existing application without having to modify any settings in IIS? It
would be great if I could just drop this code on the server and have it
run "inside" the current application.
Thanks,
justin
re:
> Now I know the answer. Hopefully that works.
Shouldn't you test that it works BEFORE saying that you know the answer ?
re:
> It would be great if I could just drop this code on the server
> and have it run "inside" the current application.
As long as you drop the code in a subdirectory of your
application's directory, everything should work fine.
Juan T. Llibre
ASP.NET MVP
http://asp.net.do/foros/
Foros de ASP.NET en Espaol
Ven, y hablemos de ASP.NET...
======================
"fenway" <justin.cutroni@.gmail.com> wrote in message
news:1116605577.929924.293220@.g14g2000cwa.googlegroups.com...
> THANK YOU!!!! Once I get ahold of the sys admin that's what I'll tell
> him to do. I had read some similar things but was unsure if I needed
> to make this sub-directory it's own application. Now I know the
> answer. Hopefully that works.
> Question, is there a way to create ASP.NET code that plugs into the
> existing application without having to modify any settings in IIS? It
> would be great if I could just drop this code on the server and have it
> run "inside" the current application.
> Thanks,
> justin
>
True, I should test it before stating that it works.
So, If I'm reading your note correctly, I should be able to drop my
application in a sub-folder of an existing application and it should
run correctly? I tried that and got an error. Plus I tried to change
web.config to display a more verbose error message but it's still
display the friendly error message.
re:
> I should be able to drop my application in a sub-folder of an
> existing application and it should run correctly?
That's not what you asked.
You asked if you could drop *code* in a sub-folder
of an existing, and whether it would run correctly.
It *will* run correctly, if you drop it as *code*.
What you are attempting to do is *nest* applications, which since
ASP 1.0 has been *verboten* ( forbidden ), because it leads to
*kaput*, i.e., the end of your application.
If you want a different application, create a different application.
If you want a sub-application, just run it in a sub-directory of your main a
pplication.
You don't have to run a sub-application as a *different* application.
If you do, that application won't be able
to share any values with your main application
Juan T. Llibre
ASP.NET MVP
http://asp.net.do/foros/
Foros de ASP.NET en Espaol
Ven, y hablemos de ASP.NET...
======================
"fenway" <justin.cutroni@.gmail.com> wrote in message
news:1116606296.822178.125240@.z14g2000cwz.googlegroups.com...
> True, I should test it before stating that it works.
> So, If I'm reading your note correctly, I should be able to drop my
> application in a sub-folder of an existing application and it should
> run correctly? I tried that and got an error. Plus I tried to change
> web.config to display a more verbose error message but it's still
> display the friendly error message.
>

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.

Trouble programatically getting form values on PostBack

I am using the following web controls (list shortened to not bore you!):

protected System.Web.UI.WebControls.RadioButtonList rblSymbols;
protected System.Web.UI.WebControls.CheckBox chkPublish;
protected System.Web.UI.WebControls.DropDownList ddlSubject;
protected System.Web.UI.WebControls.TextBox txtEntry;
protected System.Web.UI.WebControls.Button btnSave;
The btnSave_Click(object sender, System.EventArgs e) is properly registered in the InitializeComponent() method. Inside the btnSave_Click() method, I call another function to save to the db which works fine. However, when I attempt to reference the values of those items, they are not set properly. It's as if the IPostBackDataHandler.LoadPostData() method in the Init of the page lifecycle is not being done at all. Any ideas? So far, I have had to result to the following until this is figured out:
YUCK!:
**********************
myObj.Entry = Request["txtEntry"];
Preferred:
**********************
myObj.Entry = txtEntry.Text;
Thanks in advance for any insight you might have.
--ChadIs it possible you've disabled Viewstate at some point?

Peter,
Yes, itIS possible. In fact, I have done just that on several of my controls. Is this the problem? I will try re-enabling. I have read so much on the pros and cons of keeping it turned on. Is is safe to assume that if I wish to program as described above, I need to keep viewstate enabled?
--Chad

Heh... yeah, that could be the problem :)

ViewState is the mechanism by which your controls' properties are persisted across postbacks. If you want to grab myControl.Text, for example, you must have Viewstate enabled.

On the other hand, if you don't mind grabbing values from the Request.Form collection, you can kill Viewstate with impunity.

Cheers,


Peter - thanks for clearing this up for me! Very helpful!

--Chad

trouble retrieving data from ASPState Database

I'm trying to put together a web form that lists all current session informa
tion. The session info is stored in SQL server database (ASPState) and I'm t
rying to retreive and display using a SQLDataReader. I seem to have no troub
le querying the "ASPStateTe
mpSessions" table but when I try to write it to the page, I throw an excepti
on that basically says that there is no data to display. Is there some speci
al method you must use when performing this sort of task?
The code is as follows:
----
dim cn as new SqlConnection(ConfigurationSettings.AppSetting ("ASPState").to
String())
cn.Open()
dim cmd as new SqlCommand("select * from ASPStateTempSessions where TimeOut
= 40", cn)
dim dr as SqlDataReader
dr = cmd.ExecuteReader()
Response.Write(dr("Locked"))
----
The exception content is as follows:
System.InvalidOperationException: Invalid attempt to read when no data is pr
esent. at System.Data.SqlClient.SqlDataReader.PrepareRecord(Int32 i) at Syst
em.Data.SqlClient.SqlDataReader.GetValue(Int32 i) at System.Data.SqlClient.S
qlDataReader.get_Item(Strin
g name) at ASP.AgreementListing_aspx.Page_Load(Object Sender, EventArgs E) i
n C:\Inetpub\wwwroot\onehour\AgreementList
ing.aspx:line 82when using a datareader, you have to first call the "read" method.
dr = cmd.ExecuteReader()
dr.read()
Response.Write(dr("Locked"))
OR to get all rows:
do while dr.read()
Response.Write(dr("Locked"))
loop (i think)
"Glenn Venzke" <GlennVenzke@.discussions.microsoft.com> wrote in message
news:BBA23A84-4649-4967-8AA3-6D98648C0555@.microsoft.com...
> I'm trying to put together a web form that lists all current session
information. The session info is stored in SQL server database (ASPState)
and I'm trying to retreive and display using a SQLDataReader. I seem to have
no trouble querying the "ASPStateTempSessions" table but when I try to write
it to the page, I throw an exception that basically says that there is no
data to display. Is there some special method you must use when performing
this sort of task?
> The code is as follows:
> ----
> dim cn as new SqlConnection(ConfigurationSettings.AppSetting
("ASPState").toString())
> cn.Open()
> dim cmd as new SqlCommand("select * from ASPStateTempSessions where
TimeOut = 40", cn)
> dim dr as SqlDataReader
> dr = cmd.ExecuteReader()
> Response.Write(dr("Locked"))
>
> ----
> The exception content is as follows:
> System.InvalidOperationException: Invalid attempt to read when no data is
present. at System.Data.SqlClient.SqlDataReader.PrepareRecord(Int32 i) at
System.Data.SqlClient.SqlDataReader.GetValue(Int32 i) at
System.Data.SqlClient.SqlDataReader.get_Item(String name) at
ASP.AgreementListing_aspx.Page_Load(Object Sender, EventArgs E) in
C:\Inetpub\wwwroot\onehour\AgreementList
ing.aspx:line 82
Boy, am I a dope! I thought datareader.read worked along the lines of record
set.EOF. I thought it was a simple boolean property that told you if any rec
ords were returned or not. But it is actually a method that returns a boolea
n. I guess you learn someth
ing new every day. Thanks much!!
"mark" wrote:

> when using a datareader, you have to first call the "read" method.
> dr = cmd.ExecuteReader()
> dr.read()
> Response.Write(dr("Locked"))
> OR to get all rows:
> do while dr.read()
> Response.Write(dr("Locked"))
> loop (i think)
>
>
> "Glenn Venzke" <GlennVenzke@.discussions.microsoft.com> wrote in message
> news:BBA23A84-4649-4967-8AA3-6D98648C0555@.microsoft.com...
> information. The session info is stored in SQL server database (ASPState)
> and I'm trying to retreive and display using a SQLDataReader. I seem to ha
ve
> no trouble querying the "ASPStateTempSessions" table but when I try to wri
te
> it to the page, I throw an exception that basically says that there is no
> data to display. Is there some special method you must use when performing
> this sort of task?
> ("ASPState").toString())
> TimeOut = 40", cn)
> present. at System.Data.SqlClient.SqlDataReader.PrepareRecord(Int32 i) at
> System.Data.SqlClient.SqlDataReader.GetValue(Int32 i) at
> System.Data.SqlClient.SqlDataReader.get_Item(String name) at
> ASP.AgreementListing_aspx.Page_Load(Object Sender, EventArgs E) in
> C:\Inetpub\wwwroot\onehour\AgreementList
ing.aspx:line 82
>
>

Saturday, March 24, 2012

trouble retrieving data from ASPState Database

I'm trying to put together a web form that lists all current session information. The session info is stored in SQL server database (ASPState) and I'm trying to retreive and display using a SQLDataReader. I seem to have no trouble querying the "ASPStateTempSessions" table but when I try to write it to the page, I throw an exception that basically says that there is no data to display. Is there some special method you must use when performing this sort of task?
The code is as follows:
------------------
dim cn as new SqlConnection(ConfigurationSettings.AppSetting ("ASPState").toString())
cn.Open()
dim cmd as new SqlCommand("select * from ASPStateTempSessions where TimeOut = 40", cn)
dim dr as SqlDataReader
dr = cmd.ExecuteReader()
Response.Write(dr("Locked"))

------------------
The exception content is as follows:

System.InvalidOperationException: Invalid attempt to read when no data is present. at System.Data.SqlClient.SqlDataReader.PrepareRecord( Int32 i) at System.Data.SqlClient.SqlDataReader.GetValue(Int32 i) at System.Data.SqlClient.SqlDataReader.get_Item(Strin g name) at ASP.AgreementListing_aspx.Page_Load(Object Sender, EventArgs E) in C:\Inetpub\wwwroot\onehour\AgreementListing.aspx:l ine 82when using a datareader, you have to first call the "read" method.

dr = cmd.ExecuteReader()
dr.read()
Response.Write(dr("Locked"))

OR to get all rows:

do while dr.read()
Response.Write(dr("Locked"))
loop (i think)

"Glenn Venzke" <GlennVenzke@.discussions.microsoft.com> wrote in message
news:BBA23A84-4649-4967-8AA3-6D98648C0555@.microsoft.com...
> I'm trying to put together a web form that lists all current session
information. The session info is stored in SQL server database (ASPState)
and I'm trying to retreive and display using a SQLDataReader. I seem to have
no trouble querying the "ASPStateTempSessions" table but when I try to write
it to the page, I throw an exception that basically says that there is no
data to display. Is there some special method you must use when performing
this sort of task?
> The code is as follows:
> ------------------
> dim cn as new SqlConnection(ConfigurationSettings.AppSetting
("ASPState").toString())
> cn.Open()
> dim cmd as new SqlCommand("select * from ASPStateTempSessions where
TimeOut = 40", cn)
> dim dr as SqlDataReader
> dr = cmd.ExecuteReader()
> Response.Write(dr("Locked"))
>
> ------------------
> The exception content is as follows:
> System.InvalidOperationException: Invalid attempt to read when no data is
present. at System.Data.SqlClient.SqlDataReader.PrepareRecord( Int32 i) at
System.Data.SqlClient.SqlDataReader.GetValue(Int32 i) at
System.Data.SqlClient.SqlDataReader.get_Item(Strin g name) at
ASP.AgreementListing_aspx.Page_Load(Object Sender, EventArgs E) in
C:\Inetpub\wwwroot\onehour\AgreementListing.aspx:l ine 82
Boy, am I a dope! I thought datareader.read worked along the lines of recordset.EOF. I thought it was a simple boolean property that told you if any records were returned or not. But it is actually a method that returns a boolean. I guess you learn something new every day. Thanks much!!

"mark" wrote:

> when using a datareader, you have to first call the "read" method.
> dr = cmd.ExecuteReader()
> dr.read()
> Response.Write(dr("Locked"))
> OR to get all rows:
> do while dr.read()
> Response.Write(dr("Locked"))
> loop (i think)
>
>
> "Glenn Venzke" <GlennVenzke@.discussions.microsoft.com> wrote in message
> news:BBA23A84-4649-4967-8AA3-6D98648C0555@.microsoft.com...
> > I'm trying to put together a web form that lists all current session
> information. The session info is stored in SQL server database (ASPState)
> and I'm trying to retreive and display using a SQLDataReader. I seem to have
> no trouble querying the "ASPStateTempSessions" table but when I try to write
> it to the page, I throw an exception that basically says that there is no
> data to display. Is there some special method you must use when performing
> this sort of task?
> > The code is as follows:
> > ------------------
> > dim cn as new SqlConnection(ConfigurationSettings.AppSetting
> ("ASPState").toString())
> > cn.Open()
> > dim cmd as new SqlCommand("select * from ASPStateTempSessions where
> TimeOut = 40", cn)
> > dim dr as SqlDataReader
> > dr = cmd.ExecuteReader()
> > Response.Write(dr("Locked"))
> > ------------------
> > The exception content is as follows:
> > System.InvalidOperationException: Invalid attempt to read when no data is
> present. at System.Data.SqlClient.SqlDataReader.PrepareRecord( Int32 i) at
> System.Data.SqlClient.SqlDataReader.GetValue(Int32 i) at
> System.Data.SqlClient.SqlDataReader.get_Item(Strin g name) at
> ASP.AgreementListing_aspx.Page_Load(Object Sender, EventArgs E) in
> C:\Inetpub\wwwroot\onehour\AgreementListing.aspx:l ine 82
>

Trouble sending email with ASP.NET 2.0

I have an ASP.NET 2.0 application that is supposed to send an email after a
certain form is submitted. When it tries to send the email, I receive the
following error:
Transaction failed. The server response was: njsokalski@dotnet.itags.org.hotmail.com:
Recipient address rejected: Access denied
(in the error message, the part with the email address was displayed as
<myemailaddress>, but you will probably see a link because our news viewers
think they know what we want). I know that the address is correct, so what
is it that the server didn't like about it? Is it saying I don't have
permission to use the SMTP server (I was pretty sure I was, but this is the
first time I am sending email from this server)? Is there something wrong
with my code? Any help would be appreciated. Thanks.
--
Nathan Sokalski
njsokalski@dotnet.itags.org.hotmail.com
http://www.nathansokalski.com/On Fri, 5 Jan 2007 03:55:44 -0500, "Nathan Sokalski"
<njsokalski@.hotmail.com> wrote:

> Is there something wrong
>with my code? Any help would be appreciated. Thanks.
You didn't provide your code, so it is hard to tell.
However, this works for me:
Try
Dim mail As New Mail.MailMessage()
mail.From = New Mail.MailAddress("mail@.mail.somewhere",
"Subject")
mail.To.Add("another@.mail.somewhere")
mail.Subject = "Subject"
mail.Body = "Body"
Dim smtp As New Mail.SmtpClient("mail.planprojekt.dk")
smtp.Credentials = New
NetworkCredential("mail@.mail.somewhere", "password")
smtp.Send(mail)
bEmailSent = True
Catch ex As Exception
Exit Sub
End Try
/Snedker
If you are using the machine's local SMTP Service,
you may need to add a Smarthost or domains (e.g., "*.com", "*.net")
so that email sent through it is allowed to be sent out or relayed.
Peter
Site: http://www.eggheadcafe.com
UnBlog: http://petesbloggerama.blogspot.com
Short urls & more: http://ittyurl.net
"Nathan Sokalski" wrote:

> I have an ASP.NET 2.0 application that is supposed to send an email after
a
> certain form is submitted. When it tries to send the email, I receive the
> following error:
>
> Transaction failed. The server response was: njsokalski@.hotmail.com:
> Recipient address rejected: Access denied
>
> (in the error message, the part with the email address was displayed as
> <myemailaddress>, but you will probably see a link because our news viewer
s
> think they know what we want). I know that the address is correct, so what
> is it that the server didn't like about it? Is it saying I don't have
> permission to use the SMTP server (I was pretty sure I was, but this is th
e
> first time I am sending email from this server)? Is there something wrong
> with my code? Any help would be appreciated. Thanks.
> --
> Nathan Sokalski
> njsokalski@.hotmail.com
> http://www.nathansokalski.com/
>
>
The code I am using is as follows:
Private Sub SendEmailNotification()
Dim confsender As New
SmtpClient(System.Configuration.ConfigurationManager.AppSettings("smtpserver
"))
Dim confirmation As New MailMessage()
confirmation.IsBodyHtml = False
confirmation.From = New MailAddress("fromaddress@.mydomain.com")
confirmation.To.Add("njsokalski@.hotmail.com")
confirmation.Subject = "My Subject"
confirmation.Body = "My Body"
confsender.Send(confirmation)
End Sub
Thanks.
--
Nathan Sokalski
njsokalski@.hotmail.com
http://www.nathansokalski.com/
"Morten Snedker" <morten_spammenot_ATdbconsult.dk> wrote in message
news:2p6sp2dqb6qkfg0j60i3gt12iqvhdgcj70@.
4ax.com...
> On Fri, 5 Jan 2007 03:55:44 -0500, "Nathan Sokalski"
> <njsokalski@.hotmail.com> wrote:
>
> You didn't provide your code, so it is hard to tell.
> However, this works for me:
> Try
> Dim mail As New Mail.MailMessage()
> mail.From = New Mail.MailAddress("mail@.mail.somewhere",
> "Subject")
> mail.To.Add("another@.mail.somewhere")
> mail.Subject = "Subject"
> mail.Body = "Body"
> Dim smtp As New Mail.SmtpClient("mail.planprojekt.dk")
> smtp.Credentials = New
> NetworkCredential("mail@.mail.somewhere", "password")
> smtp.Send(mail)
> bEmailSent = True
> Catch ex As Exception
> Exit Sub
> End Try
>
> /Snedker

Trouble sending email with ASP.NET 2.0

I have an ASP.NET 2.0 application that is supposed to send an email after a
certain form is submitted. When it tries to send the email, I receive the
following error:

Transaction failed. The server response was: njsokalski@dotnet.itags.org.hotmail.com:
Recipient address rejected: Access denied

(in the error message, the part with the email address was displayed as
<myemailaddress>, but you will probably see a link because our news viewers
think they know what we want). I know that the address is correct, so what
is it that the server didn't like about it? Is it saying I don't have
permission to use the SMTP server (I was pretty sure I was, but this is the
first time I am sending email from this server)? Is there something wrong
with my code? Any help would be appreciated. Thanks.
--
Nathan Sokalski
njsokalski@dotnet.itags.org.hotmail.com
http://www.nathansokalski.com/On Fri, 5 Jan 2007 03:55:44 -0500, "Nathan Sokalski"
<njsokalski@.hotmail.comwrote:

Quote:

Originally Posted by

Is there something wrong
>with my code? Any help would be appreciated. Thanks.


You didn't provide your code, so it is hard to tell.

However, this works for me:

Try
Dim mail As New Mail.MailMessage()

mail.From = New Mail.MailAddress("mail@.mail.somewhere",
"Subject")
mail.To.Add("another@.mail.somewhere")

mail.Subject = "Subject"
mail.Body = "Body"

Dim smtp As New Mail.SmtpClient("mail.planprojekt.dk")
smtp.Credentials = New
NetworkCredential("mail@.mail.somewhere", "password")
smtp.Send(mail)

bEmailSent = True
Catch ex As Exception
Exit Sub
End Try

/Snedker
The code I am using is as follows:

Private Sub SendEmailNotification()
Dim confsender As New
SmtpClient(System.Configuration.ConfigurationManag er.AppSettings("smtpserver"))
Dim confirmation As New MailMessage()
confirmation.IsBodyHtml = False
confirmation.From = New MailAddress("fromaddress@.mydomain.com")
confirmation.To.Add("njsokalski@.hotmail.com")
confirmation.Subject = "My Subject"
confirmation.Body = "My Body"

confsender.Send(confirmation)
End Sub

Thanks.
--
Nathan Sokalski
njsokalski@.hotmail.com
http://www.nathansokalski.com/
"Morten Snedker" <morten_spammenot_ATdbconsult.dkwrote in message
news:2p6sp2dqb6qkfg0j60i3gt12iqvhdgcj70@.4ax.com...

Quote:

Originally Posted by

On Fri, 5 Jan 2007 03:55:44 -0500, "Nathan Sokalski"
<njsokalski@.hotmail.comwrote:
>

Quote:

Originally Posted by

>Is there something wrong
>>with my code? Any help would be appreciated. Thanks.


>
You didn't provide your code, so it is hard to tell.
>
However, this works for me:
>
Try
Dim mail As New Mail.MailMessage()
>
mail.From = New Mail.MailAddress("mail@.mail.somewhere",
"Subject")
mail.To.Add("another@.mail.somewhere")
>
mail.Subject = "Subject"
mail.Body = "Body"
>
Dim smtp As New Mail.SmtpClient("mail.planprojekt.dk")
smtp.Credentials = New
NetworkCredential("mail@.mail.somewhere", "password")
smtp.Send(mail)
>
bEmailSent = True
Catch ex As Exception
Exit Sub
End Try
>
>
/Snedker

Trouble viewing ASP buttons on a web form

Hi,

I am a long-time java programmer, trying to learn about ASP.NET. I am trying write a simple "Hello, Browser" web form using the Visual Studio .NET web form designer. The form consists of a web form label and 3 web form buttons. The buttons don't perform any function. However, when I build and run the program, a browser pops up, but only displays the label and not the buttons. Can anyone tell me what the problem might be? Is it a problem with the code, or maybe some settings?

Thank YouCan you post your code?
If you installed IIS after Visual Studio .NET, you have to register ASP.NET with IIS. You can do this by opening a VS.NET command prompt (i.e. Start > Programs > Visual Studio .NET > Tools > Command Prompt) and typing:

aspnet_regiis -i

That should do the trick. ;)
Super!

This forum is such an amazing resource. I would have never guessed that on my own. Stanley Tan, your solution worked.

Thank you. Thank You. Thank You.

Thursday, March 22, 2012

Trouble with emailing

I use the following code to email from a form :

Sub sendEmail(Src As Object, E As EventArgs)
Dim msg as New MailMessage()
msg.To = "paul@dotnet.itags.org.mydomain.com"
msg.From = "fred@dotnet.itags.org.mydomain.com"
msg.Subject = "TESTING"
msg.BodyFormat = MailFormat.Html
msg.Body = "TESTING BODY"
SmtpMail.SmtpServer = "localhost"
SmtpMail.Send(msg)
msg = Nothing

end sub

But I keep getting the error message :

"The server rejected one or more recipient addresses. The server response was: 550 5.7.1 Unable to relay for paul@dotnet.itags.org.mydomain.com"

Can anyone tell me what Im doing wrong ?

P.S. I do have the appropriate Include at the top of my page:)

You are getting this error because in smtp server your relay list is empty.

Try this :

1. In IIS right-click on the Default SMTP Virtual Server and select Properties.
2. In the Properties dialog box, selec the Access tab.
3. Click on the Relay button.
4. In the Relay Restrictions dialog box, select the Allow except the list below radio button.

trouble with form in C#

Hi there
I've got a littel problem. I've samo form which should add data to database.
Everythinks goes OK, but I'd like to have some alert messege when samobody
would like to add another user with the same nick. Now my aplication in that
case goes down.
This is code
void Button1_Click(object sender, EventArgs e) { SqlConnection c =
baza_danych.Polacz();
SqlCommand cmd = new SqlCommand("insert into klient
(IDklienta,Nazwisko,Imie,Adres,Miasto,Ha
slo) values ( '"+ IDklienta.Text +"'
,'" + Nazwisko.Text + "','" + Imie.Text + "','" + Adres.Text + "','" +
Miasto.Text + "','" + Haslo.Text + "')", c);
SqlDataReader dr = cmd.ExecuteReader();
bool test; test=dr.HasRows; if (test==true) { dr.Read(); Label1.Text =
"choose another nick"; } else { Label1.Text = "You are added to database"; }
dr.Close();
c.Close(); }
TIA
AdamWithout knowing the design of your datatable I cannot be sure, but a pretty
safe bet is that you get an SqlException because a duplicate row (nick is
the unique column?) already exists.
There are a number of ways to solve this.
1) Handle the exception - You should always have exception handlers, but
they should not be used to handle expected errors, but exceptional
circumstances.
2) Rewrite the code, using a stored procedure. The stored procedure will
typically do a query and only insert when needed. With your code you are
very vulnerable to Sql injection attacks.
3) Do a query for the nick first. Only insert if it does not already exist.
The third option is possibly quickest, the second is by far the best in
terms of security, transactions and performance. And to make your life even
easier, check out the data application block (from
www.microsoft.com/patterns, if I remember correctly, but also from
gotdotnet)
Reidar Husmo
"adam" <adabi@.poczta.onet.pl> wrote in message
news:ct123c$rgo$1@.news.onet.pl...
> Hi there
> I've got a littel problem. I've samo form which should add data to
> database.
> Everythinks goes OK, but I'd like to have some alert messege when samobody
> would like to add another user with the same nick. Now my aplication in
> that
> case goes down.
> This is code
> void Button1_Click(object sender, EventArgs e) { SqlConnection c =
> baza_danych.Polacz();
> SqlCommand cmd = new SqlCommand("insert into klient
> (IDklienta,Nazwisko,Imie,Adres,Miasto,Ha
slo) values ( '"+ IDklienta.Text
> +"'
> ,'" + Nazwisko.Text + "','" + Imie.Text + "','" + Adres.Text + "','" +
> Miasto.Text + "','" + Haslo.Text + "')", c);
> SqlDataReader dr = cmd.ExecuteReader();
> bool test; test=dr.HasRows; if (test==true) { dr.Read(); Label1.Text =
> "choose another nick"; } else { Label1.Text = "You are added to
> database"; }
> dr.Close();
> c.Close(); }
> TIA
> Adam
>
Thanks for a reply, but I'm just starting witch asp.net and I'haven't got
any idea how to corect my project. Would you mind if I send you my *.asp
file?
If not, give me your email adress
TIA
Adam

> Without knowing the design of your datatable I cannot be sure, but a
pretty
> safe bet is that you get an SqlException because a duplicate row (nick is
> the unique column?) already exists.
> There are a number of ways to solve this.
> 1) Handle the exception - You should always have exception handlers, but
> they should not be used to handle expected errors, but exceptional
> circumstances.
> 2) Rewrite the code, using a stored procedure. The stored procedure will
> typically do a query and only insert when needed. With your code you are
> very vulnerable to Sql injection attacks.
> 3) Do a query for the nick first. Only insert if it does not already
exist.
> The third option is possibly quickest, the second is by far the best in
> terms of security, transactions and performance. And to make your life
even
> easier, check out the data application block (from
> www.microsoft.com/patterns, if I remember correctly, but also from
> gotdotnet)
> Reidar Husmo
>
Adam,
Assuming that IDklienta is your nick (nickname? means username?), the
easiest approach is to just put a unique constraint on the
dbo.klient.IDklienta column. This ensures that any attempt to insert a new
row with the same value in that column will fail.
In your C#, code, you can catch the failure using try/catch
[PSEUDOCODE]
...
Label1.Text = ""; // clear the error
SqlConnection c = baza_danych.Polacz();
SqlCommand cmd = new SqlCommand("insert into klient
(IDklienta,Nazwisko,Imie,Adres,Miasto,Ha
slo) values ( '"+ IDklienta.Text +"'
,'" + Nazwisko.Text + "','" + Imie.Text + "','" + Adres.Text + "','" +
Miasto.Text + "','" + Haslo.Text + "')", c);
try
{
// attempt your insert here
cmd.ExecuteNonQuery ();
// insert was successful
Label1.Text = "You are added to database";
}
catch (SqlException ex)
{
// check specifically for a constraint violation error
// display an appropriate error message
Label1.Text = "choose another nick";
}
finally
{
c.Close();
}
...
I don't normally see a SqlDataReader and ExecuteReader() used on an insert
statement. I'm not sure whether it would work or not, but it's probably
cleaner to use ExecuteNonQuery () instead, as demonstrated above.
Also, do not forget the escape apostrophes in your strings. If a user
enters an apostrophe (') in one of your textboxes, your SQL string breaks
since apostrophes are the SQL string delimiter. You can solve this easily
e.g.;
IDklienta.Text.Replace("'","''"); // replace single apostrophe with
double-apostrophe
Although using paramaterized SQL would be a cleaner approach.
/// M
"adam" <adabi@.poczta.onet.pl> wrote in message
news:ct123c$rgo$1@.news.onet.pl...
> Hi there
> I've got a littel problem. I've samo form which should add data to
database.
> Everythinks goes OK, but I'd like to have some alert messege when samobody
> would like to add another user with the same nick. Now my aplication in
that
> case goes down.
> This is code
> void Button1_Click(object sender, EventArgs e) { SqlConnection c =
> baza_danych.Polacz();
> SqlCommand cmd = new SqlCommand("insert into klient
> (IDklienta,Nazwisko,Imie,Adres,Miasto,Ha
slo) values ( '"+ IDklienta.Text
+"'
> ,'" + Nazwisko.Text + "','" + Imie.Text + "','" + Adres.Text + "','" +
> Miasto.Text + "','" + Haslo.Text + "')", c);
> SqlDataReader dr = cmd.ExecuteReader();
> bool test; test=dr.HasRows; if (test==true) { dr.Read(); Label1.Text =
> "choose another nick"; } else { Label1.Text = "You are added to
database"; }
> dr.Close();
> c.Close(); }
> TIA
> Adam
>
Thanks a lot!
Adam
Uytkownik "MWells" <outbound__at_sygnal.com> napisa w wiadomoci
news:ukSqjoZAFHA.2568@.TK2MSFTNGP10.phx.gbl...
> Adam,
> Assuming that IDklienta is your nick (nickname? means username?), the
> easiest approach is to just put a unique constraint on the
> dbo.klient.IDklienta column. This ensures that any attempt to insert a
new
> row with the same value in that column will fail.
> In your C#, code, you can catch the failure using try/catch
> [PSEUDOCODE]
> ...
> Label1.Text = ""; // clear the error
> SqlConnection c = baza_danych.Polacz();
> SqlCommand cmd = new SqlCommand("insert into klient
> (IDklienta,Nazwisko,Imie,Adres,Miasto,Ha
slo) values ( '"+ IDklienta.Text
+"'
> ,'" + Nazwisko.Text + "','" + Imie.Text + "','" + Adres.Text + "','" +
> Miasto.Text + "','" + Haslo.Text + "')", c);
> try
> {
> // attempt your insert here
> cmd.ExecuteNonQuery ();
> // insert was successful
> Label1.Text = "You are added to database";
> }
> catch (SqlException ex)
> {
> // check specifically for a constraint violation error
> // display an appropriate error message
> Label1.Text = "choose another nick";
> }
> finally
> {
> c.Close();
> }
> ...
> I don't normally see a SqlDataReader and ExecuteReader() used on an insert
> statement. I'm not sure whether it would work or not, but it's probably
> cleaner to use ExecuteNonQuery () instead, as demonstrated above.
> Also, do not forget the escape apostrophes in your strings. If a user
> enters an apostrophe (') in one of your textboxes, your SQL string breaks
> since apostrophes are the SQL string delimiter. You can solve this easily
> e.g.;
> IDklienta.Text.Replace("'","''"); // replace single apostrophe with
> double-apostrophe
> Although using paramaterized SQL would be a cleaner approach.
> /// M
> "adam" <adabi@.poczta.onet.pl> wrote in message
> news:ct123c$rgo$1@.news.onet.pl...
> database.
samobody
> that
> +"'
> database"; }
>

trouble with form in C#

Hi there
I've got a littel problem. I've samo form which should add data to database.
Everythinks goes OK, but I'd like to have some alert messege when samobody
would like to add another user with the same nick. Now my aplication in that
case goes down.
This is code

void Button1_Click(object sender, EventArgs e) { SqlConnection c =
baza_danych.Polacz();
SqlCommand cmd = new SqlCommand("insert into klient
(IDklienta,Nazwisko,Imie,Adres,Miasto,Haslo) values ( '"+ IDklienta.Text +"'
,'" + Nazwisko.Text + "','" + Imie.Text + "','" + Adres.Text + "','" +
Miasto.Text + "','" + Haslo.Text + "')", c);
SqlDataReader dr = cmd.ExecuteReader();
bool test; test=dr.HasRows; if (test==true) { dr.Read(); Label1.Text =
"choose another nick"; } else { Label1.Text = "You are added to database"; }
dr.Close();
c.Close(); }

TIA
AdamWithout knowing the design of your datatable I cannot be sure, but a pretty
safe bet is that you get an SqlException because a duplicate row (nick is
the unique column?) already exists.
There are a number of ways to solve this.
1) Handle the exception - You should always have exception handlers, but
they should not be used to handle expected errors, but exceptional
circumstances.
2) Rewrite the code, using a stored procedure. The stored procedure will
typically do a query and only insert when needed. With your code you are
very vulnerable to Sql injection attacks.
3) Do a query for the nick first. Only insert if it does not already exist.
The third option is possibly quickest, the second is by far the best in
terms of security, transactions and performance. And to make your life even
easier, check out the data application block (from
www.microsoft.com/patterns, if I remember correctly, but also from
gotdotnet)

Reidar Husmo

"adam" <adabi@.poczta.onet.pl> wrote in message
news:ct123c$rgo$1@.news.onet.pl...
> Hi there
> I've got a littel problem. I've samo form which should add data to
> database.
> Everythinks goes OK, but I'd like to have some alert messege when samobody
> would like to add another user with the same nick. Now my aplication in
> that
> case goes down.
> This is code
> void Button1_Click(object sender, EventArgs e) { SqlConnection c =
> baza_danych.Polacz();
> SqlCommand cmd = new SqlCommand("insert into klient
> (IDklienta,Nazwisko,Imie,Adres,Miasto,Haslo) values ( '"+ IDklienta.Text
> +"'
> ,'" + Nazwisko.Text + "','" + Imie.Text + "','" + Adres.Text + "','" +
> Miasto.Text + "','" + Haslo.Text + "')", c);
> SqlDataReader dr = cmd.ExecuteReader();
> bool test; test=dr.HasRows; if (test==true) { dr.Read(); Label1.Text =
> "choose another nick"; } else { Label1.Text = "You are added to
> database"; }
> dr.Close();
> c.Close(); }
> TIA
> Adam
Thanks for a reply, but I'm just starting witch asp.net and I'haven't got
any idea how to corect my project. Would you mind if I send you my *.asp
file?
If not, give me your email adress
TIA
Adam

> Without knowing the design of your datatable I cannot be sure, but a
pretty
> safe bet is that you get an SqlException because a duplicate row (nick is
> the unique column?) already exists.
> There are a number of ways to solve this.
> 1) Handle the exception - You should always have exception handlers, but
> they should not be used to handle expected errors, but exceptional
> circumstances.
> 2) Rewrite the code, using a stored procedure. The stored procedure will
> typically do a query and only insert when needed. With your code you are
> very vulnerable to Sql injection attacks.
> 3) Do a query for the nick first. Only insert if it does not already
exist.
> The third option is possibly quickest, the second is by far the best in
> terms of security, transactions and performance. And to make your life
even
> easier, check out the data application block (from
> www.microsoft.com/patterns, if I remember correctly, but also from
> gotdotnet)
> Reidar Husmo
Adam,

Assuming that IDklienta is your nick (nickname? means username?), the
easiest approach is to just put a unique constraint on the
dbo.klient.IDklienta column. This ensures that any attempt to insert a new
row with the same value in that column will fail.

In your C#, code, you can catch the failure using try/catch

[PSEUDOCODE]

...
Label1.Text = ""; // clear the error

SqlConnection c = baza_danych.Polacz();

SqlCommand cmd = new SqlCommand("insert into klient
(IDklienta,Nazwisko,Imie,Adres,Miasto,Haslo) values ( '"+ IDklienta.Text +"'
,'" + Nazwisko.Text + "','" + Imie.Text + "','" + Adres.Text + "','" +
Miasto.Text + "','" + Haslo.Text + "')", c);

try
{
// attempt your insert here
cmd.ExecuteNonQuery ();

// insert was successful
Label1.Text = "You are added to database";
}
catch (SqlException ex)
{
// check specifically for a constraint violation error

// display an appropriate error message
Label1.Text = "choose another nick";
}
finally
{
c.Close();
}
...

I don't normally see a SqlDataReader and ExecuteReader() used on an insert
statement. I'm not sure whether it would work or not, but it's probably
cleaner to use ExecuteNonQuery () instead, as demonstrated above.

Also, do not forget the escape apostrophes in your strings. If a user
enters an apostrophe (') in one of your textboxes, your SQL string breaks
since apostrophes are the SQL string delimiter. You can solve this easily
e.g.;

IDklienta.Text.Replace("'","''"); // replace single apostrophe with
double-apostrophe

Although using paramaterized SQL would be a cleaner approach.

/// M

"adam" <adabi@.poczta.onet.pl> wrote in message
news:ct123c$rgo$1@.news.onet.pl...
> Hi there
> I've got a littel problem. I've samo form which should add data to
database.
> Everythinks goes OK, but I'd like to have some alert messege when samobody
> would like to add another user with the same nick. Now my aplication in
that
> case goes down.
> This is code
> void Button1_Click(object sender, EventArgs e) { SqlConnection c =
> baza_danych.Polacz();
> SqlCommand cmd = new SqlCommand("insert into klient
> (IDklienta,Nazwisko,Imie,Adres,Miasto,Haslo) values ( '"+ IDklienta.Text
+"'
> ,'" + Nazwisko.Text + "','" + Imie.Text + "','" + Adres.Text + "','" +
> Miasto.Text + "','" + Haslo.Text + "')", c);
> SqlDataReader dr = cmd.ExecuteReader();
> bool test; test=dr.HasRows; if (test==true) { dr.Read(); Label1.Text =
> "choose another nick"; } else { Label1.Text = "You are added to
database"; }
> dr.Close();
> c.Close(); }
> TIA
> Adam
Thanks a lot!
Adam

Uytkownik "MWells" <outbound__at_sygnal.com> napisa w wiadomoci
news:ukSqjoZAFHA.2568@.TK2MSFTNGP10.phx.gbl...
> Adam,
> Assuming that IDklienta is your nick (nickname? means username?), the
> easiest approach is to just put a unique constraint on the
> dbo.klient.IDklienta column. This ensures that any attempt to insert a
new
> row with the same value in that column will fail.
> In your C#, code, you can catch the failure using try/catch
> [PSEUDOCODE]
> ...
> Label1.Text = ""; // clear the error
> SqlConnection c = baza_danych.Polacz();
> SqlCommand cmd = new SqlCommand("insert into klient
> (IDklienta,Nazwisko,Imie,Adres,Miasto,Haslo) values ( '"+ IDklienta.Text
+"'
> ,'" + Nazwisko.Text + "','" + Imie.Text + "','" + Adres.Text + "','" +
> Miasto.Text + "','" + Haslo.Text + "')", c);
> try
> {
> // attempt your insert here
> cmd.ExecuteNonQuery ();
> // insert was successful
> Label1.Text = "You are added to database";
> }
> catch (SqlException ex)
> {
> // check specifically for a constraint violation error
> // display an appropriate error message
> Label1.Text = "choose another nick";
> }
> finally
> {
> c.Close();
> }
> ...
> I don't normally see a SqlDataReader and ExecuteReader() used on an insert
> statement. I'm not sure whether it would work or not, but it's probably
> cleaner to use ExecuteNonQuery () instead, as demonstrated above.
> Also, do not forget the escape apostrophes in your strings. If a user
> enters an apostrophe (') in one of your textboxes, your SQL string breaks
> since apostrophes are the SQL string delimiter. You can solve this easily
> e.g.;
> IDklienta.Text.Replace("'","''"); // replace single apostrophe with
> double-apostrophe
> Although using paramaterized SQL would be a cleaner approach.
> /// M
> "adam" <adabi@.poczta.onet.pl> wrote in message
> news:ct123c$rgo$1@.news.onet.pl...
> > Hi there
> > I've got a littel problem. I've samo form which should add data to
> database.
> > Everythinks goes OK, but I'd like to have some alert messege when
samobody
> > would like to add another user with the same nick. Now my aplication in
> that
> > case goes down.
> > This is code
> > void Button1_Click(object sender, EventArgs e) { SqlConnection c =
> > baza_danych.Polacz();
> > SqlCommand cmd = new SqlCommand("insert into klient
> > (IDklienta,Nazwisko,Imie,Adres,Miasto,Haslo) values ( '"+ IDklienta.Text
> +"'
> > ,'" + Nazwisko.Text + "','" + Imie.Text + "','" + Adres.Text + "','" +
> > Miasto.Text + "','" + Haslo.Text + "')", c);
> > SqlDataReader dr = cmd.ExecuteReader();
> > bool test; test=dr.HasRows; if (test==true) { dr.Read(); Label1.Text =
> > "choose another nick"; } else { Label1.Text = "You are added to
> database"; }
> > dr.Close();
> > c.Close(); }
> > TIA
> > Adam

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

trouble with web forms

im trying to get a table from a microsoft access database on a simple
web form using visual basic.net. ive set up the database as a file
dsn.
this is my connection string:
DBQ=C:\Program Files\Microsoft
Office\OFFICE11\SAMPLES\Northwind.mdb;DefaultDir=C:\Program
Files\Microsoft Office\OFFICE11\SAMPLES;Driver={Microsof
t Access Driver
(*.mdb)};DriverId=25;FIL=MS Access;FILEDSN=C:\Program Files\Common
Files\ODBC\Data
Sources\test2. dsn;MaxBufferSize=2048;MaxScanRows=8;Pag
eTimeout=5;SafeTransac
tions=0;Threads=3;UID=admin;UserCommitSy
nc=Yes;
works fine when i try it with a windows form, however with the webform,
when i try it, i get the following errors because of line69 :
ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver]General error
Unable to open registry key 'Temporary (volatile) Jet DSN for process
0x3a4 Thread 0x720 DBC 0x437aa4 Jet'. ERROR [IM006] [Microsoft][ODBC
Driver Manager] Driver's SQLSetConnectAttr failed ERROR [HY000]
[Microsoft][ODBC Microsoft Access Driver]General error Unable to open
registry key 'Temporary (volatile) Jet DSN for process 0x3a4 Thread
0x720 DBC 0x437aa4 Jet'. ERROR [HY000] [Microsoft][ODBC Microsoft
Access Driver] Could not use '(unknown)'; file already in use. ERROR
[HY000] [Microsoft][ODBC Microsoft Access Driver]General error Unable
to open registry key 'Temporary (volatile) Jet DSN for process 0x3a4
Thread 0x720 DBC 0x437aa4 Jet'. ERROR [HY000] [Microsoft][ODBC
Microsoft Access Driver]General error Unable to open registry key
'Temporary (volatile) Jet DSN for process 0x3a4 Thread 0x720 DBC
0x437aa4 Jet'. ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver]
Could not use '(unknown)'; file already in use.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Data.Odbc.OdbcException: ERROR [HY000]
[Microsoft][ODBC Microsoft Access Driver]General error Unable to open
registry key 'Temporary (volatile) Jet DSN for process 0x3a4 Thread
0x720 DBC 0x437aa4 Jet'. ERROR [IM006] [Microsoft][ODBC Driver Manager]
Driver's SQLSetConnectAttr failed ERROR [HY000] [Microsoft][ODBC
Microsoft Access Driver]General error Unable to open registry key
'Temporary (volatile) Jet DSN for process 0x3a4 Thread 0x720 DBC
0x437aa4 Jet'. ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver]
Could not use '(unknown)'; file already in use. ERROR [HY000]
[Microsoft][ODBC Microsoft Access Driver]General error Unable to open
registry key 'Temporary (volatile) Jet DSN for process 0x3a4 Thread
0x720 DBC 0x437aa4 Jet'. ERROR [HY000] [Microsoft][ODBC Microsoft
Access Driver]General error Unable to open registry key 'Temporary
(volatile) Jet DSN for process 0x3a4 Thread 0x720 DBC 0x437aa4 Jet'.
ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver] Could not use
'(unknown)'; file already in use.
Source Error:
Line 67: Private Sub Page_Load(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles MyBase.Load
Line 68: DataSet11.Clear()
Line 69: OdbcDataAdapter1.Fill(DataSet11)
Line 70: DataGrid1.DataBind()
Line 71: End Sub
Source File: c:\inetpub\wwwroot\TestWeb1\WebForm1.aspx.vb Line: 69
Stack Trace:
[OdbcException: ERROR [HY000] [Microsoft][ODBC Microsoft Access
Driver]General error Unable to open registry key 'Temporary (volatile)
Jet DSN for process 0x3a4 Thread 0x720 DBC 0x437aa4 Jet'.
ERROR [IM006] [Microsoft][ODBC Driver Manager] Driver's
SQLSetConnectAttr failed
ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver]General error
Unable to open registry key 'Temporary (volatile) Jet DSN for process
0x3a4 Thread 0x720 DBC 0x437aa4 Jet'.
ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver] Could not use
'(unknown)'; file already in use.
ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver]General error
Unable to open registry key 'Temporary (volatile) Jet DSN for process
0x3a4 Thread 0x720 DBC 0x437aa4 Jet'.
ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver]General error
Unable to open registry key 'Temporary (volatile) Jet DSN for process
0x3a4 Thread 0x720 DBC 0x437aa4 Jet'.
ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver] Could not use
'(unknown)'; file already in use.]
System.Data.Odbc.OdbcConnection.Open()
System.Data.Common.DbDataAdapter.QuietOpen(IDbConnection connection,
ConnectionState& originalState)
System.Data.Common.DbDataAdapter.FillFromCommand(Object data, Int32
startRecord, Int32 maxRecords, String srcTable, IDbCommand command,
CommandBehavior behavior)
System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32
startRecord, Int32 maxRecords, String srcTable, IDbCommand command,
CommandBehavior behavior)
System.Data.Common.DbDataAdapter.Fill(DataSet dataSet)
TestWeb1.WebForm1.Page_Load(Object sender, EventArgs e) in
c:\inetpub\wwwroot\TestWeb1\WebForm1.aspx.vb:69
System.Web.UI.Control.OnLoad(EventArgs e)
System.Web.UI.Control.LoadRecursive()
System.Web.UI.Page.ProcessRequestMain()
This is my code:
Public Class WebForm1
Inherits System.Web.UI.Page
#Region " Web Form Designer Generated Code "
'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub
InitializeComponent()
Me.OdbcSelectCommand1 = New System.Data.Odbc.OdbcCommand
Me.OdbcInsertCommand1 = New System.Data.Odbc.OdbcCommand
Me.OdbcConnection1 = New System.Data.Odbc.OdbcConnection
Me.OdbcDataAdapter1 = New System.Data.Odbc.OdbcDataAdapter
Me.DataSet11 = New TestWeb1.DataSet1
CType(Me.DataSet11,
System.ComponentModel.ISupportInitialize).BeginInit()
'
'OdbcSelectCommand1
'
Me.OdbcSelectCommand1.CommandText = "SELECT ShipperID,
CompanyName, Phone FROM Shippers"
Me.OdbcSelectCommand1.Connection = Me.OdbcConnection1
'
'OdbcInsertCommand1
'
Me.OdbcInsertCommand1.CommandText = "INSERT INTO
Shippers(CompanyName, Phone) VALUES (?, ?)"
Me.OdbcInsertCommand1.Connection = Me.OdbcConnection1
Me.OdbcInsertCommand1.Parameters.Add(New
System.Data.Odbc.OdbcParameter("CompanyName",
System.Data.Odbc.OdbcType.NVarChar, 40, "CompanyName"))
Me.OdbcInsertCommand1.Parameters.Add(New
System.Data.Odbc.OdbcParameter("Phone",
System.Data.Odbc.OdbcType.NVarChar, 24, "Phone"))
'
'OdbcConnection1
'
Me.OdbcConnection1.ConnectionString =
" PageTimeout=5;MaxScanRows=8;DefaultDir=C
:\Program Files\Microsoft
Office\OFFICE11" & _
"\SAMPLES;FILEDSN=C:\Program Files\Common Files\ODBC\Data
Sources\test2.dsn;Drive" & _
"rId=25;DBQ=C:\Program Files\Microsoft
Office\OFFICE11\SAMPLES\Northwind.mdb;User" & _
"CommitSync=Yes;FIL=MS Access;UID=admin;Driver={Microsoft
Access Driver (*.mdb)};" & _
" MaxBufferSize=2048;Threads=3;SafeTransac
tions=0"
'
'OdbcDataAdapter1
'
Me.OdbcDataAdapter1.InsertCommand = Me.OdbcInsertCommand1
Me.OdbcDataAdapter1.SelectCommand = Me.OdbcSelectCommand1
Me.OdbcDataAdapter1.TableMappings.AddRange(New
System.Data.Common.DataTableMapping() {New
System.Data.Common.DataTableMapping("Table", "Shippers", New
System.Data.Common.DataColumnMapping() {New
System.Data.Common.DataColumnMapping("ShipperID", "ShipperID"), New
System.Data.Common.DataColumnMapping("CompanyName", "CompanyName"), New
System.Data.Common.DataColumnMapping("Phone", "Phone")})})
'
'DataSet11
'
Me.DataSet11.DataSetName = "DataSet1"
Me.DataSet11.Locale = New
System.Globalization.CultureInfo("en-IE")
CType(Me.DataSet11,
System.ComponentModel.ISupportInitialize).EndInit()
End Sub
Protected WithEvents OdbcSelectCommand1 As
System.Data.Odbc.OdbcCommand
Protected WithEvents OdbcInsertCommand1 As
System.Data.Odbc.OdbcCommand
Protected WithEvents OdbcConnection1 As
System.Data.Odbc.OdbcConnection
Protected WithEvents OdbcDataAdapter1 As
System.Data.Odbc.OdbcDataAdapter
Protected WithEvents DataSet11 As TestWeb1.DataSet1
Protected WithEvents DataGrid1 As
System.Web.UI.WebControls.DataGrid
'NOTE: The following placeholder declaration is required by the Web
Form Designer.
'Do not delete or move it.
Private designerPlaceholderDeclaration As System.Object
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub
#End Region
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
DataSet11.Clear()
OdbcDataAdapter1.Fill(DataSet11)
DataGrid1.DataBind()
End Sub
End Class
iv been tryin to sort this for a couple of days but am completely at a
loss as to how to sort this. Can anyone help?Well, I could be wrong since I haven't seen every detail of your setup or
code, but that looks like a very strange connection string. Here are some
things I would check:
1. Directories rarely start with the drive letter (C:) when dealing with the
web.
2. Your connection string looks much more complicated than necessary. Here
is the line that I use to create my connections in all the websites I have
created that use Access databases (and they have been on different servers,
so unless you have a strange setup I'm guessing it will work for you too):
Dim myconnection As New
OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=" &
Server.MapPath("/mydatabase.mdb"))
Just modify the last part to be the correct path to your *.mdb file.
3. Check the permissions on the *.mdb file to make sure ASPNET has
permission to access it.
Although something that I am kind of getting the impression of is that you
require a more full-featured and secure database, Access was not really
intended for web-related stuff. If you have a very big company or plan to
use the database heavily, I would put in the effort and money to buy either
Oracle or SQL Server (you would probably prefer SQL Server since you are
coming from Access). I am only a student, but ASP.NET and Web Development
are my areas of concentration and these are things I have been taught and
gained through experience and articles I have read. Good Luck!
--
Nathan Sokalski
njsokalski@.hotmail.com
http://www.nathansokalski.com/
<somersbar@.yahoo.com> wrote in message
news:1140106859.776998.150120@.z14g2000cwz.googlegroups.com...
> im trying to get a table from a microsoft access database on a simple
> web form using visual basic.net. ive set up the database as a file
> dsn.
> this is my connection string:
> DBQ=C:\Program Files\Microsoft
> Office\OFFICE11\SAMPLES\Northwind.mdb;DefaultDir=C:\Program
> Files\Microsoft Office\OFFICE11\SAMPLES;Driver={Microsof
t Access Driver
> (*.mdb)};DriverId=25;FIL=MS Access;FILEDSN=C:\Program Files\Common
> Files\ODBC\Data
> Sources\test2. dsn;MaxBufferSize=2048;MaxScanRows=8;Pag
eTimeout=5;SafeTrans
actions=0;Threads=3;UID=admin;UserCommit
Sync=Yes;
>
> works fine when i try it with a windows form, however with the webform,
> when i try it, i get the following errors because of line69 :
>
> ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver]General error
> Unable to open registry key 'Temporary (volatile) Jet DSN for process
> 0x3a4 Thread 0x720 DBC 0x437aa4 Jet'. ERROR [IM006] [Microsoft][ODBC
> Driver Manager] Driver's SQLSetConnectAttr failed ERROR [HY000]
> [Microsoft][ODBC Microsoft Access Driver]General error Unable to open
> registry key 'Temporary (volatile) Jet DSN for process 0x3a4 Thread
> 0x720 DBC 0x437aa4 Jet'. ERROR [HY000] [Microsoft][ODBC Microsoft
> Access Driver] Could not use '(unknown)'; file already in use. ERROR
> [HY000] [Microsoft][ODBC Microsoft Access Driver]General error Unable
> to open registry key 'Temporary (volatile) Jet DSN for process 0x3a4
> Thread 0x720 DBC 0x437aa4 Jet'. ERROR [HY000] [Microsoft][ODBC
> Microsoft Access Driver]General error Unable to open registry key
> 'Temporary (volatile) Jet DSN for process 0x3a4 Thread 0x720 DBC
> 0x437aa4 Jet'. ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver]
> Could not use '(unknown)'; file already in use.
> Description: An unhandled exception occurred during the execution of
> the current web request. Please review the stack trace for more
> information about the error and where it originated in the code.
> Exception Details: System.Data.Odbc.OdbcException: ERROR [HY000]
> [Microsoft][ODBC Microsoft Access Driver]General error Unable to open
> registry key 'Temporary (volatile) Jet DSN for process 0x3a4 Thread
> 0x720 DBC 0x437aa4 Jet'. ERROR [IM006] [Microsoft][ODBC Driver Manager]
> Driver's SQLSetConnectAttr failed ERROR [HY000] [Microsoft][ODBC
> Microsoft Access Driver]General error Unable to open registry key
> 'Temporary (volatile) Jet DSN for process 0x3a4 Thread 0x720 DBC
> 0x437aa4 Jet'. ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver]
> Could not use '(unknown)'; file already in use. ERROR [HY000]
> [Microsoft][ODBC Microsoft Access Driver]General error Unable to open
> registry key 'Temporary (volatile) Jet DSN for process 0x3a4 Thread
> 0x720 DBC 0x437aa4 Jet'. ERROR [HY000] [Microsoft][ODBC Microsoft
> Access Driver]General error Unable to open registry key 'Temporary
> (volatile) Jet DSN for process 0x3a4 Thread 0x720 DBC 0x437aa4 Jet'.
> ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver] Could not use
> '(unknown)'; file already in use.
> Source Error:
> Line 67: Private Sub Page_Load(ByVal sender As System.Object, ByVal
> e As System.EventArgs) Handles MyBase.Load
> Line 68: DataSet11.Clear()
> Line 69: OdbcDataAdapter1.Fill(DataSet11)
> Line 70: DataGrid1.DataBind()
> Line 71: End Sub
>
> Source File: c:\inetpub\wwwroot\TestWeb1\WebForm1.aspx.vb Line: 69
> Stack Trace:
> [OdbcException: ERROR [HY000] [Microsoft][ODBC Microsoft Access
> Driver]General error Unable to open registry key 'Temporary (volatile)
> Jet DSN for process 0x3a4 Thread 0x720 DBC 0x437aa4 Jet'.
> ERROR [IM006] [Microsoft][ODBC Driver Manager] Driver's
> SQLSetConnectAttr failed
> ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver]General error
> Unable to open registry key 'Temporary (volatile) Jet DSN for process
> 0x3a4 Thread 0x720 DBC 0x437aa4 Jet'.
> ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver] Could not use
> '(unknown)'; file already in use.
> ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver]General error
> Unable to open registry key 'Temporary (volatile) Jet DSN for process
> 0x3a4 Thread 0x720 DBC 0x437aa4 Jet'.
> ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver]General error
> Unable to open registry key 'Temporary (volatile) Jet DSN for process
> 0x3a4 Thread 0x720 DBC 0x437aa4 Jet'.
> ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver] Could not use
> '(unknown)'; file already in use.]
> System.Data.Odbc.OdbcConnection.Open()
> System.Data.Common.DbDataAdapter.QuietOpen(IDbConnection connection,
> ConnectionState& originalState)
> System.Data.Common.DbDataAdapter.FillFromCommand(Object data, Int32
> startRecord, Int32 maxRecords, String srcTable, IDbCommand command,
> CommandBehavior behavior)
> System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32
> startRecord, Int32 maxRecords, String srcTable, IDbCommand command,
> CommandBehavior behavior)
> System.Data.Common.DbDataAdapter.Fill(DataSet dataSet)
> TestWeb1.WebForm1.Page_Load(Object sender, EventArgs e) in
> c:\inetpub\wwwroot\TestWeb1\WebForm1.aspx.vb:69
> System.Web.UI.Control.OnLoad(EventArgs e)
> System.Web.UI.Control.LoadRecursive()
> System.Web.UI.Page.ProcessRequestMain()
>
>
> This is my code:
> Public Class WebForm1
> Inherits System.Web.UI.Page
> #Region " Web Form Designer Generated Code "
> 'This call is required by the Web Form Designer.
> <System.Diagnostics.DebuggerStepThrough()> Private Sub
> InitializeComponent()
> Me.OdbcSelectCommand1 = New System.Data.Odbc.OdbcCommand
> Me.OdbcInsertCommand1 = New System.Data.Odbc.OdbcCommand
> Me.OdbcConnection1 = New System.Data.Odbc.OdbcConnection
> Me.OdbcDataAdapter1 = New System.Data.Odbc.OdbcDataAdapter
> Me.DataSet11 = New TestWeb1.DataSet1
> CType(Me.DataSet11,
> System.ComponentModel.ISupportInitialize).BeginInit()
> '
> 'OdbcSelectCommand1
> '
> Me.OdbcSelectCommand1.CommandText = "SELECT ShipperID,
> CompanyName, Phone FROM Shippers"
> Me.OdbcSelectCommand1.Connection = Me.OdbcConnection1
> '
> 'OdbcInsertCommand1
> '
> Me.OdbcInsertCommand1.CommandText = "INSERT INTO
> Shippers(CompanyName, Phone) VALUES (?, ?)"
> Me.OdbcInsertCommand1.Connection = Me.OdbcConnection1
> Me.OdbcInsertCommand1.Parameters.Add(New
> System.Data.Odbc.OdbcParameter("CompanyName",
> System.Data.Odbc.OdbcType.NVarChar, 40, "CompanyName"))
> Me.OdbcInsertCommand1.Parameters.Add(New
> System.Data.Odbc.OdbcParameter("Phone",
> System.Data.Odbc.OdbcType.NVarChar, 24, "Phone"))
> '
> 'OdbcConnection1
> '
> Me.OdbcConnection1.ConnectionString =
> " PageTimeout=5;MaxScanRows=8;DefaultDir=C
:\Program Files\Microsoft
> Office\OFFICE11" & _
> "\SAMPLES;FILEDSN=C:\Program Files\Common Files\ODBC\Data
> Sources\test2.dsn;Drive" & _
> "rId=25;DBQ=C:\Program Files\Microsoft
> Office\OFFICE11\SAMPLES\Northwind.mdb;User" & _
> "CommitSync=Yes;FIL=MS Access;UID=admin;Driver={Microsoft
> Access Driver (*.mdb)};" & _
> " MaxBufferSize=2048;Threads=3;SafeTransac
tions=0"
> '
> 'OdbcDataAdapter1
> '
> Me.OdbcDataAdapter1.InsertCommand = Me.OdbcInsertCommand1
> Me.OdbcDataAdapter1.SelectCommand = Me.OdbcSelectCommand1
> Me.OdbcDataAdapter1.TableMappings.AddRange(New
> System.Data.Common.DataTableMapping() {New
> System.Data.Common.DataTableMapping("Table", "Shippers", New
> System.Data.Common.DataColumnMapping() {New
> System.Data.Common.DataColumnMapping("ShipperID", "ShipperID"), New
> System.Data.Common.DataColumnMapping("CompanyName", "CompanyName"), New
> System.Data.Common.DataColumnMapping("Phone", "Phone")})})
> '
> 'DataSet11
> '
> Me.DataSet11.DataSetName = "DataSet1"
> Me.DataSet11.Locale = New
> System.Globalization.CultureInfo("en-IE")
> CType(Me.DataSet11,
> System.ComponentModel.ISupportInitialize).EndInit()
> End Sub
> Protected WithEvents OdbcSelectCommand1 As
> System.Data.Odbc.OdbcCommand
> Protected WithEvents OdbcInsertCommand1 As
> System.Data.Odbc.OdbcCommand
> Protected WithEvents OdbcConnection1 As
> System.Data.Odbc.OdbcConnection
> Protected WithEvents OdbcDataAdapter1 As
> System.Data.Odbc.OdbcDataAdapter
> Protected WithEvents DataSet11 As TestWeb1.DataSet1
> Protected WithEvents DataGrid1 As
> System.Web.UI.WebControls.DataGrid
> 'NOTE: The following placeholder declaration is required by the Web
> Form Designer.
> 'Do not delete or move it.
> Private designerPlaceholderDeclaration As System.Object
> Private Sub Page_Init(ByVal sender As System.Object, ByVal e As
> System.EventArgs) Handles MyBase.Init
> 'CODEGEN: This method call is required by the Web Form Designer
> 'Do not modify it using the code editor.
> InitializeComponent()
> End Sub
> #End Region
> Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
> System.EventArgs) Handles MyBase.Load
> DataSet11.Clear()
> OdbcDataAdapter1.Fill(DataSet11)
> DataGrid1.DataBind()
> End Sub
> End Class
>
> iv been tryin to sort this for a couple of days but am completely at a
> loss as to how to sort this. Can anyone help?
>
Do you have Office installed on your server?
--
Christopher A. Reed
"The oxen are slow, but the earth is patient."
<somersbar@.yahoo.com> wrote in message
news:1140106859.776998.150120@.z14g2000cwz.googlegroups.com...
> im trying to get a table from a microsoft access database on a simple
> web form using visual basic.net. ive set up the database as a file
> dsn.
> this is my connection string:
> DBQ=C:\Program Files\Microsoft
> Office\OFFICE11\SAMPLES\Northwind.mdb;DefaultDir=C:\Program
> Files\Microsoft Office\OFFICE11\SAMPLES;Driver={Microsof
t Access Driver
> (*.mdb)};DriverId=25;FIL=MS Access;FILEDSN=C:\Program Files\Common
> Files\ODBC\Data
> Sources\test2. dsn;MaxBufferSize=2048;MaxScanRows=8;Pag
eTimeout=5;SafeTrans
actions=0;Threads=3;UID=admin;UserCommit
Sync=Yes;
>
> works fine when i try it with a windows form, however with the webform,
> when i try it, i get the following errors because of line69 :
>
> ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver]General error
> Unable to open registry key 'Temporary (volatile) Jet DSN for process
> 0x3a4 Thread 0x720 DBC 0x437aa4 Jet'. ERROR [IM006] [Microsoft][ODBC
> Driver Manager] Driver's SQLSetConnectAttr failed ERROR [HY000]
> [Microsoft][ODBC Microsoft Access Driver]General error Unable to open
> registry key 'Temporary (volatile) Jet DSN for process 0x3a4 Thread
> 0x720 DBC 0x437aa4 Jet'. ERROR [HY000] [Microsoft][ODBC Microsoft
> Access Driver] Could not use '(unknown)'; file already in use. ERROR
> [HY000] [Microsoft][ODBC Microsoft Access Driver]General error Unable
> to open registry key 'Temporary (volatile) Jet DSN for process 0x3a4
> Thread 0x720 DBC 0x437aa4 Jet'. ERROR [HY000] [Microsoft][ODBC
> Microsoft Access Driver]General error Unable to open registry key
> 'Temporary (volatile) Jet DSN for process 0x3a4 Thread 0x720 DBC
> 0x437aa4 Jet'. ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver]
> Could not use '(unknown)'; file already in use.
> Description: An unhandled exception occurred during the execution of
> the current web request. Please review the stack trace for more
> information about the error and where it originated in the code.
> Exception Details: System.Data.Odbc.OdbcException: ERROR [HY000]
> [Microsoft][ODBC Microsoft Access Driver]General error Unable to open
> registry key 'Temporary (volatile) Jet DSN for process 0x3a4 Thread
> 0x720 DBC 0x437aa4 Jet'. ERROR [IM006] [Microsoft][ODBC Driver Manager]
> Driver's SQLSetConnectAttr failed ERROR [HY000] [Microsoft][ODBC
> Microsoft Access Driver]General error Unable to open registry key
> 'Temporary (volatile) Jet DSN for process 0x3a4 Thread 0x720 DBC
> 0x437aa4 Jet'. ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver]
> Could not use '(unknown)'; file already in use. ERROR [HY000]
> [Microsoft][ODBC Microsoft Access Driver]General error Unable to open
> registry key 'Temporary (volatile) Jet DSN for process 0x3a4 Thread
> 0x720 DBC 0x437aa4 Jet'. ERROR [HY000] [Microsoft][ODBC Microsoft
> Access Driver]General error Unable to open registry key 'Temporary
> (volatile) Jet DSN for process 0x3a4 Thread 0x720 DBC 0x437aa4 Jet'.
> ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver] Could not use
> '(unknown)'; file already in use.
> Source Error:
> Line 67: Private Sub Page_Load(ByVal sender As System.Object, ByVal
> e As System.EventArgs) Handles MyBase.Load
> Line 68: DataSet11.Clear()
> Line 69: OdbcDataAdapter1.Fill(DataSet11)
> Line 70: DataGrid1.DataBind()
> Line 71: End Sub
>
> Source File: c:\inetpub\wwwroot\TestWeb1\WebForm1.aspx.vb Line: 69
> Stack Trace:
> [OdbcException: ERROR [HY000] [Microsoft][ODBC Microsoft Access
> Driver]General error Unable to open registry key 'Temporary (volatile)
> Jet DSN for process 0x3a4 Thread 0x720 DBC 0x437aa4 Jet'.
> ERROR [IM006] [Microsoft][ODBC Driver Manager] Driver's
> SQLSetConnectAttr failed
> ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver]General error
> Unable to open registry key 'Temporary (volatile) Jet DSN for process
> 0x3a4 Thread 0x720 DBC 0x437aa4 Jet'.
> ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver] Could not use
> '(unknown)'; file already in use.
> ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver]General error
> Unable to open registry key 'Temporary (volatile) Jet DSN for process
> 0x3a4 Thread 0x720 DBC 0x437aa4 Jet'.
> ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver]General error
> Unable to open registry key 'Temporary (volatile) Jet DSN for process
> 0x3a4 Thread 0x720 DBC 0x437aa4 Jet'.
> ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver] Could not use
> '(unknown)'; file already in use.]
> System.Data.Odbc.OdbcConnection.Open()
> System.Data.Common.DbDataAdapter.QuietOpen(IDbConnection connection,
> ConnectionState& originalState)
> System.Data.Common.DbDataAdapter.FillFromCommand(Object data, Int32
> startRecord, Int32 maxRecords, String srcTable, IDbCommand command,
> CommandBehavior behavior)
> System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32
> startRecord, Int32 maxRecords, String srcTable, IDbCommand command,
> CommandBehavior behavior)
> System.Data.Common.DbDataAdapter.Fill(DataSet dataSet)
> TestWeb1.WebForm1.Page_Load(Object sender, EventArgs e) in
> c:\inetpub\wwwroot\TestWeb1\WebForm1.aspx.vb:69
> System.Web.UI.Control.OnLoad(EventArgs e)
> System.Web.UI.Control.LoadRecursive()
> System.Web.UI.Page.ProcessRequestMain()
>
>
> This is my code:
> Public Class WebForm1
> Inherits System.Web.UI.Page
> #Region " Web Form Designer Generated Code "
> 'This call is required by the Web Form Designer.
> <System.Diagnostics.DebuggerStepThrough()> Private Sub
> InitializeComponent()
> Me.OdbcSelectCommand1 = New System.Data.Odbc.OdbcCommand
> Me.OdbcInsertCommand1 = New System.Data.Odbc.OdbcCommand
> Me.OdbcConnection1 = New System.Data.Odbc.OdbcConnection
> Me.OdbcDataAdapter1 = New System.Data.Odbc.OdbcDataAdapter
> Me.DataSet11 = New TestWeb1.DataSet1
> CType(Me.DataSet11,
> System.ComponentModel.ISupportInitialize).BeginInit()
> '
> 'OdbcSelectCommand1
> '
> Me.OdbcSelectCommand1.CommandText = "SELECT ShipperID,
> CompanyName, Phone FROM Shippers"
> Me.OdbcSelectCommand1.Connection = Me.OdbcConnection1
> '
> 'OdbcInsertCommand1
> '
> Me.OdbcInsertCommand1.CommandText = "INSERT INTO
> Shippers(CompanyName, Phone) VALUES (?, ?)"
> Me.OdbcInsertCommand1.Connection = Me.OdbcConnection1
> Me.OdbcInsertCommand1.Parameters.Add(New
> System.Data.Odbc.OdbcParameter("CompanyName",
> System.Data.Odbc.OdbcType.NVarChar, 40, "CompanyName"))
> Me.OdbcInsertCommand1.Parameters.Add(New
> System.Data.Odbc.OdbcParameter("Phone",
> System.Data.Odbc.OdbcType.NVarChar, 24, "Phone"))
> '
> 'OdbcConnection1
> '
> Me.OdbcConnection1.ConnectionString =
> " PageTimeout=5;MaxScanRows=8;DefaultDir=C
:\Program Files\Microsoft
> Office\OFFICE11" & _
> "\SAMPLES;FILEDSN=C:\Program Files\Common Files\ODBC\Data
> Sources\test2.dsn;Drive" & _
> "rId=25;DBQ=C:\Program Files\Microsoft
> Office\OFFICE11\SAMPLES\Northwind.mdb;User" & _
> "CommitSync=Yes;FIL=MS Access;UID=admin;Driver={Microsoft
> Access Driver (*.mdb)};" & _
> " MaxBufferSize=2048;Threads=3;SafeTransac
tions=0"
> '
> 'OdbcDataAdapter1
> '
> Me.OdbcDataAdapter1.InsertCommand = Me.OdbcInsertCommand1
> Me.OdbcDataAdapter1.SelectCommand = Me.OdbcSelectCommand1
> Me.OdbcDataAdapter1.TableMappings.AddRange(New
> System.Data.Common.DataTableMapping() {New
> System.Data.Common.DataTableMapping("Table", "Shippers", New
> System.Data.Common.DataColumnMapping() {New
> System.Data.Common.DataColumnMapping("ShipperID", "ShipperID"), New
> System.Data.Common.DataColumnMapping("CompanyName", "CompanyName"), New
> System.Data.Common.DataColumnMapping("Phone", "Phone")})})
> '
> 'DataSet11
> '
> Me.DataSet11.DataSetName = "DataSet1"
> Me.DataSet11.Locale = New
> System.Globalization.CultureInfo("en-IE")
> CType(Me.DataSet11,
> System.ComponentModel.ISupportInitialize).EndInit()
> End Sub
> Protected WithEvents OdbcSelectCommand1 As
> System.Data.Odbc.OdbcCommand
> Protected WithEvents OdbcInsertCommand1 As
> System.Data.Odbc.OdbcCommand
> Protected WithEvents OdbcConnection1 As
> System.Data.Odbc.OdbcConnection
> Protected WithEvents OdbcDataAdapter1 As
> System.Data.Odbc.OdbcDataAdapter
> Protected WithEvents DataSet11 As TestWeb1.DataSet1
> Protected WithEvents DataGrid1 As
> System.Web.UI.WebControls.DataGrid
> 'NOTE: The following placeholder declaration is required by the Web
> Form Designer.
> 'Do not delete or move it.
> Private designerPlaceholderDeclaration As System.Object
> Private Sub Page_Init(ByVal sender As System.Object, ByVal e As
> System.EventArgs) Handles MyBase.Init
> 'CODEGEN: This method call is required by the Web Form Designer
> 'Do not modify it using the code editor.
> InitializeComponent()
> End Sub
> #End Region
> Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
> System.EventArgs) Handles MyBase.Load
> DataSet11.Clear()
> OdbcDataAdapter1.Fill(DataSet11)
> DataGrid1.DataBind()
> End Sub
> End Class
>
> iv been tryin to sort this for a couple of days but am completely at a
> loss as to how to sort this. Can anyone help?
>