Welcome to Dream.In.Code
Getting C# Help is Easy!

Join 118,307 C# Programmers for FREE! Ask your question and get quick answers from experts. There are 1,695 online right now! We've got more than 500 tutorials and 2,000 snippets. Join and find out why Dream.In.Code is the #1 programming help community on the internet! Registration is fast and FREE... Join Now!



Insert into MS sql database data from text boxes

 
Reply to this topicStart new topic

Insert into MS sql database data from text boxes

sraymond101
post 5 Aug, 2008 - 03:43 AM
Post #1


New D.I.C Head

*
Joined: 20 Jul, 2008
Posts: 5



Thanked 1 times
My Contributions


I don't know what is wrong with the data from the form, fFor example txtCustomerID.Text. Can someone please help?
CODE
  SqlConnection conn = new SqlConnection("SignUpConnectionString");
         SqlCommand cmd = new SqlCommand();
             string query = "INSERT INTO Customer VALUES(@CustomerID,@FirstName,@LastName,@Address,@HomePhone,@CellPhone,@Email)";

                 cmd.CommandText = query;
                 cmd.CommandType = CommandType.Text;

                 cmd.Parameters.AddWithValue("@CustomerID", txtCustomerID);
                cmd.Parameters.AddWithValue("@FirstName", txtFirtName.Text );
                 cmd.Parameters.AddWithValue("@LastName",txtLastName.Text );
                 cmd.Parameters.AddWithValue("@Address",txtAddress.Text );
                 cmd.Parameters.AddWithValue("@City",txtCity.Text );
                 cmd.Parameters.AddWithValue("@StateProvince",txtStateProvince.Text );
                 cmd.Parameters.AddWithValue("@ZipCode",txtZipCode.Text );
                 cmd.Parameters.AddWithValue("@Country",txtCountryText );
                 cmd.Parameters.AddWithValue("@HomePhone",txtHomePhone.Text );
                 cmd.Parameters.AddWithValue("@CellPhone",txtCellPhone.Text );
                 cmd.Parameters.AddWithValue("@AltPhone",txtAltPhone.Text );
                 cmd.Parameters.AddWithValue("@Email",txtEmail.Text );
                 cmd.Parameters.AddWithValue("@Status","P" );
                 cmd.Parameters.AddWithValue("@DateAdded",DateTime.Now );
                 cmd.Connection = conn;
                 conn.open;
                 cmd.ExecuteNonQuery();
User is offlineProfile CardPM

Go to the top of the page


modi123_1
post 5 Aug, 2008 - 09:06 AM
Post #2


D.I.C Regular

Group Icon
Joined: 12 Jun, 2008
Posts: 353



Thanked 7 times

Dream Kudos: 100
My Contributions


Yeah, yeah.. sorry this is not in the code tags, but this highlights some of the missing parameters and property calls.

Sray, if you are going to have parameters added to the call you best make sure they are in the insert statement or else why add them? Also to get the text from a text box you would need the property call for '.text', else you are just asking for the textbox object itself.

If this doesn't work then you'll need to tell us two things:
1. the error you are receiving.
2. your table defintion (types and names)

CODE

   SqlConnection conn = new SqlConnection("SignUpConnectionString");
         SqlCommand cmd = new SqlCommand();
             string query = "INSERT INTO Customer VALUES(@CustomerID,@FirstName,@LastName,@Address,
[color=#FF0000]@City,
@StateProvince,
@ZipCode,
@Country,[/color]

@HomePhone,@CellPhone,
[color=#FF0000]@AltPhone,[/color]
@Email[color=#FF0000],
@Status,
@DateAdded[/color]
)";

                 cmd.CommandText = query;
                 cmd.CommandType = CommandType.Text;

                 cmd.Parameters.AddWithValue("@CustomerID", txtCustomerID.TEXT);
                cmd.Parameters.AddWithValue("@FirstName", txtFirtName.Text );
                 cmd.Parameters.AddWithValue("@LastName",txtLastName.Text );
                 cmd.Parameters.AddWithValue("@Address",txtAddress.Text );
                 cmd.Parameters.AddWithValue("@City",txtCity.Text );
                 cmd.Parameters.AddWithValue("@StateProvince",txtStateProvince.Text );
                 cmd.Parameters.AddWithValue("@ZipCode",txtZipCode.Text );
                 cmd.Parameters.AddWithValue("@Country",txtCountryText );
                 cmd.Parameters.AddWithValue("@HomePhone",txtHomePhone.Text );
                 cmd.Parameters.AddWithValue("@CellPhone",txtCellPhone.Text );
                 cmd.Parameters.AddWithValue("@AltPhone",txtAltPhone.Text );
                 cmd.Parameters.AddWithValue("@Email",txtEmail.Text );
                 cmd.Parameters.AddWithValue("@Status","P" );
                 cmd.Parameters.AddWithValue("@DateAdded",DateTime.Now );
                 cmd.Connection = conn;
                 conn.open;
                 cmd.ExecuteNonQuery();
User is online!Profile CardPM

Go to the top of the page

sraymond101
post 5 Aug, 2008 - 05:45 PM
Post #3


New D.I.C Head

*
Joined: 20 Jul, 2008
Posts: 5



Thanked 1 times
My Contributions


Here is the name of my connection SignUpConnectionString in the web.config file. Here is the where the error occurs: SqlConnection conn = new SqlConnection("SignUpConnectionString");

Here the detail of the problem below:
System.ArgumentException was unhandled by user code
Message="Format of the initialization string does not conform to specification starting at index 0."
Source="System.Data"
StackTrace:
at System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String& keyname, String& keyvalue)
at System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey)
at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules)
at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous)
at System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(String connectionString, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions)
at System.Data.SqlClient.SqlConnection.ConnectionString_Set(String value)
at System.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
at System.Data.SqlClient.SqlConnection..ctor(String connectionString)
at Signup.InsertNewCuastomer() in c:\Learning\VSI\Signup.aspx.cs:line 138
at Signup.btnSignUp_Click(Object sender, EventArgs e) in c:\Learning\VSI\Signup.aspx.cs:line 104
at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:
User is offlineProfile CardPM

Go to the top of the page

eclipsed4utoo
post 6 Aug, 2008 - 05:47 AM
Post #4


D.I.C Head

**
Joined: 21 Mar, 2008
Posts: 159



Thanked 8 times
My Contributions


you are trying to assign a literal string "SignUpConnectionString" as the connection string. You will need to MANUALLY READ FROM THE Web.Config file to get the connection string.
User is offlineProfile CardPM

Go to the top of the page

sraymond101
post 6 Aug, 2008 - 06:53 PM
Post #5


New D.I.C Head

*
Joined: 20 Jul, 2008
Posts: 5



Thanked 1 times
My Contributions


QUOTE(eclipsed4utoo @ 6 Aug, 2008 - 05:47 AM) *

you are trying to assign a literal string "SignUpConnectionString" as the connection string. You will need to MANUALLY READ FROM THE Web.Config file to get the connection string.


Well, I can put the Parameter of the connection string in my code shown below, and the insert works.
//SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Learning\VSI\App_Data\vsi.mdf;Integrated Security=True;User Instance=True");

I would like to put in the web config file as shown below.
<add name="SignUpConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Learning\VSI\App_Data\vsi.mdf;Integrated Security=True;User Instance=True"
providerName=".NET Framework Data Provider for SQL Server"/>

I want use something like this.
SqlConnection conn = new SqlConnection("SignUpConnectionString");
Here is the error:
Format of the initialization string does not conform to specification starting at index 0.
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.ArgumentException: Format of the initialization string does not conform to specification starting at index 0.



SignUpConnectionString
User is offlineProfile CardPM

Go to the top of the page

PsychoCoder
post 6 Aug, 2008 - 07:00 PM
Post #6


using DIC.Core;

Group Icon
Joined: 26 Jul, 2007
Posts: 7,871



Thanked 80 times

Dream Kudos: 8050

Expert In: VB, VB.Net, C#, SQL, ASP, ASP.Net, Web Development, HTML, CSS, Win32 API, Javascript, mySQL, J#, GDI, Boo.Net

My Contributions


If storing your connection string in the web.cofig, it's easiest to create a simple method for retrieving the connection string. What's happening with you is your app is you arent retrieving the actual connection stirng, it's thinking "SignupConnectionStirng" is the actual string, when it's only the name of the connection string in the web.config. Use this method for retrieving your connection string


csharp

/// <summary>
/// method to retrieve the database connection string from the web.config
/// </summary>
/// <param name="name">name of the connection string we want (this allows us to have multiple if needed)</param>
/// <returns></returns>
public string GetConnectionString(string name)
{
try
{
//variable to hold our connection string for returning it
string connString = string.Empty;
//check to see if the user provided a connection string name
//this is for if your application has more than one connection string
if (!string.IsNullOrEmpty(name)) //a connection string name was provided
{
//get the connection string by the name provided
connString = ConfigurationManager.ConnectionStrings[name].ConnectionString;
}
else //no connection string name was provided
{
//get the default connection string
connString = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
}
_status = true;
//return the connection string to the calling method
return connString;
}
catch (Exception ex)
{
_message = ex.Message;
_status = false;
return string.Empty;
}
}


Then you can use this line

csharp

SqlConnection conn = new SqlConnection(GetConnectionString("SignUpConnectionString"));
User is online!Profile CardPM

Go to the top of the page

eclipsed4utoo
post 6 Aug, 2008 - 07:05 PM
Post #7


D.I.C Head

**
Joined: 21 Mar, 2008
Posts: 159



Thanked 8 times
My Contributions


QUOTE(sraymond101 @ 6 Aug, 2008 - 09:53 PM) *

QUOTE(eclipsed4utoo @ 6 Aug, 2008 - 05:47 AM) *

you are trying to assign a literal string "SignUpConnectionString" as the connection string. You will need to MANUALLY READ FROM THE Web.Config file to get the connection string.


Well, I can put the Parameter of the connection string in my code shown below, and the insert works.
//SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Learning\VSI\App_Data\vsi.mdf;Integrated Security=True;User Instance=True");

I would like to put in the web config file as shown below.
<add name="SignUpConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Learning\VSI\App_Data\vsi.mdf;Integrated Security=True;User Instance=True"
providerName=".NET Framework Data Provider for SQL Server"/>

I want use something like this.
SqlConnection conn = new SqlConnection("SignUpConnectionString");
Here is the error:
Format of the initialization string does not conform to specification starting at index 0.
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.ArgumentException: Format of the initialization string does not conform to specification starting at index 0.



SignUpConnectionString


So where are you telling the application to go to the Web.Config file to get the connection string? Do you really think just typing the attribute is how you retrieve information from the Web.Config file?

here is your tutorial.

http://www.csharpfriends.com/Articles/getA...x?articleID=106
User is offlineProfile CardPM

Go to the top of the page

sraymond101
post 9 Aug, 2008 - 01:30 PM
Post #8


New D.I.C Head

*
Joined: 20 Jul, 2008
Posts: 5



Thanked 1 times
My Contributions


QUOTE(PsychoCoder @ 6 Aug, 2008 - 07:00 PM) *

If storing your connection string in the web.cofig, it's easiest to create a simple method for retrieving the connection string. What's happening with you is your app is you arent retrieving the actual connection stirng, it's thinking "SignupConnectionStirng" is the actual string, when it's only the name of the connection string in the web.config. Use this method for retrieving your connection string


csharp

/// <summary>
/// method to retrieve the database connection string from the web.config
/// </summary>
/// <param name="name">name of the connection string we want (this allows us to have multiple if needed)</param>
/// <returns></returns>
public string GetConnectionString(string name)
{
try
{
//variable to hold our connection string for returning it
string connString = string.Empty;
//check to see if the user provided a connection string name
//this is for if your application has more than one connection string
if (!string.IsNullOrEmpty(name)) //a connection string name was provided
{
//get the connection string by the name provided
connString = ConfigurationManager.ConnectionStrings[name].ConnectionString;
}
else //no connection string name was provided
{
//get the default connection string
connString = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
}
_status = true;
//return the connection string to the calling method
return connString;
}
catch (Exception ex)
{
_message = ex.Message;
_status = false;
return string.Empty;
}
}


Then you can use this line

csharp

SqlConnection conn = new SqlConnection(GetConnectionString("SignUpConnectionString"));




Thank you. This approach gets the connection string as I expected it. Can I put this methode in a class so I can refer to it from anywhere in my application.
User is offlineProfile CardPM

Go to the top of the page

Fast ReplyReply to this topicStart new topic
Time is now: 10/10/08 11:39AM

Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month