I understand that this may be considered a duplicate question, but I am at an impasse and i do not know what it is I am doing wrong, I need help. The duplicate question said to use OLEDB in order to write to the Microsoft Access file, where as before I was using the SQL connection to accomplish my task. As far as i can tell there are no syntax, logic, or runtime errors and Visual Studios doesnt have an issue either.
When i run the code and go to add a new entry to the Microsoft Access Database Table, it says it worked, but when I go and look at the file there is NOTHING there. Someone please help me, I have goe through all the links, all the web pages, all the search engines, and I dont know what is wrong. I would love to learn what is wrong and how to fix it so I wont ever have to ask for help again.
Currently I am a college student and I am working on a team assignment. Our task, is to create a window that will take input from a user and then add it as a entry into an Microsoft Access File as if it were a SQL database.
The issue we are having is that we are trying to add the new entry to a local Microsoft Access file under the table named Artist. I have connected to an actual SQL server before and no one else in my group has, even worse no one has done this with using a Microsoft Access file on our PC either.
I have added the Database (Microsoft Access File) in Visual Studios using the Database Configuration Wizard. At first I was using straight SQL do to this and then i was told i need to use OLEDB in order to do this. SO I have implemented in the code and for some reason I still cannot get it to work. If anyone can give me a hand and tell me what it is I am doing wrong, I would greatly appreciate it.
Details that I believe are important for anyone to help me:
The name of the table I am attempting to write a new entry to: Artist
Name of the Microsoft Access File: Kays.accdb
Location of the Microsoft Access file: C:\KayDB\Kays.accdb (local machine)
Once again I would greatly appreciate any help that anyone can give me. I really am curious as to why the code is not working, please help me understand.
My code is as follows:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Kay
{
public partial class Kay_Green : Form
{
string Username,Fname, Mname, Lname, streetaddress, city, phonenumber, emailaddress, zipcode, taxIDnummber, state;
string[,] SQLTable = new string[0, 10];
public Kay_Green()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{//Save Button
/*Upon clicking the save button, gather all info and save it into an temp array.
Then send it to the SQL database.*/
/*The order of the data in the array will be the same order in the SQL table.*/
Fname = tbFirstName.Text;
Mname = tbMiddleInitial.Text;
Lname = tbLastName.Text;
streetaddress = tbStreet.Text;
city = tbCity.Text;
state = cbState.Text;
phonenumber = tbPhoneNumber.Text;
emailaddress = tbEmailAddress.Text;
zipcode = tbZipCode.Text;
taxIDnummber = tbTaxID.Text;
Username = tbUserName.Text;
/*SQLTable[0,0] = taxIDnummber;
SQLTable[0,1] = Fname;
SQLTable[0,2] = Mname;
SQLTable[0,3] = Lname;
SQLTable[0,4] = streetaddress;
SQLTable[0,5] = city;
SQLTable[0,6] = state;
SQLTable[0,7] = zipcode;
SQLTable[0,8] = phonenumber;
SQLTable[0,9] = emailaddress;*/
/*Below is the details for the SQL connection*/
string connectstring="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\KayDB\\Kays.accdb";
OleDbConnection connection=new OleDbConnection(connectstring);
OleDbCommand command;
OleDbDataAdapter adapter;
DataTable dt = new DataTable();
string sql ="Insert into ARTIST values ('" + taxIDnummber + "','"
+ emailaddress + "','" + Fname + "','" + Mname + "','"
+ Lname + "','" + phonenumber+"','"+ Username + "','"
+ streetaddress + "','" + city + "','" +state+ "','"
+ zipcode + "')";
try
{
connection.Open();
command = new OleDbCommand(sql, connection);
MessageBox.Show("Connection Open And data added to table! ");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! " + ex.StackTrace.ToString());
}
/*Above is the details for the SQL connection*/
}
private void btnCancel_Click(object sender, EventArgs e)
{//Cancel Button
tbCity.Clear();
tbEmailAddress.Clear();
tbFirstName.Clear();
tbLastName.Clear();
tbMiddleInitial.Clear();
tbPhoneNumber.Clear();
tbStreet.Clear();
tbTaxID.Clear();
tbZipCode.Clear();
tbUserName.Clear();
Close();//Go back to switchboard from here
}
private void btnClear_Click(object sender, EventArgs e)
{//Clear button
tbCity.Clear();
tbEmailAddress.Clear();
tbFirstName.Clear();
tbLastName.Clear();
tbMiddleInitial.Clear();
tbPhoneNumber.Clear();
tbStreet.Clear();
tbTaxID.Clear();
tbZipCode.Clear();
tbUserName.Clear();
}
}
}
This code
command = new OleDbCommand(sql, connection);
sets up a command but does not run it
you need to run this afterwards:
command.ExecuteNonQuery();
This has nothing to do with connection strings
Related
I'm new to coding in C# and have looked around but finding it hard to extrapolate an answer for my problem.
I'm currently just trying to get to grips with adding text and selected text from a combobox into a simple database table. However when I try to add the information I get an error of SqlException was unhandled. I've looked at other answers and saw it maybe something to do with adding a connection, which I've tried but it's still not working...
My code and error message as in the image link below but just in case here is my code also,
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace SavetoDbTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection test = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\User\\Documents\\Visual Studio 2015\\Projects\\SavetoDbTest\\SavetoDbTest\\Hobbie.mdf;Integrated Security=True"))
{
using (SqlCommand again = new SqlCommand())
{
again.CommandText = "INSERT INTO Table Values('" + textBox1.Text + "', '" + comboBox1.Text + "')";
again.Parameters.AddWithValue("#Name", textBox1.Text);
again.Parameters.AddWithValue("#Hobby", comboBox1.Text);
again.Connection = test;
test.Open();
again.ExecuteNonQuery();
test.Close();
MessageBox.Show("Data Entry Successful");
}
}
}
}
}
+1 for trying to use parameterized queries! But you're not doing it right :-)
again.CommandText = "INSERT INTO Table Values('" + textBox1.Text + "', '" + comboBox1.Text + "')";
again.Parameters.AddWithValue("#Name", textBox1.Text);
again.Parameters.AddWithValue("#Hobby", comboBox1.Text);
This add parameters when the query string doesn't expect them. Probably this is also the cause for the exception you're seeing.
Your query string must look like this:
again.CommandText = "INSERT INTO [Table] Values(#Name, #Hobby)";
Also, TABLE is a reserved word in SQL. So if your table is named Table, you should wrap it in square brackets.
Use this instead of:
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection test = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\User\\Documents\\Visual Studio 2015\\Projects\\SavetoDbTest\\SavetoDbTest\\Hobbie.mdf;Integrated Security=True"))
{
using (SqlCommand again = new SqlCommand())
{
again.CommandText = "INSERT INTO [TableName] Values(#Name,#Hobby)";
again.Parameters.AddWithValue("#Name", textBox1.Text);
again.Parameters.AddWithValue("#Hobby", comboBox1.Text);
again.Connection = test;
test.Open();
again.ExecuteNonQuery();
test.Close();
MessageBox.Show("Data Entry Successful");
}
}
}
As mentioned by PaulF it is always a good practise to use Try..Catch block. It will give you the exception message if the code doesn't works for you. Here you go.
private void button1_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection test = new SqlConnection("YourConnectionStringName"))
{
using (SqlCommand again = new SqlCommand())
{
again.CommandText = "INSERT INTO Table Values(#Name,#Hobby)";
again.Parameters.AddWithValue("#Name", textBox1.Text);
again.Parameters.AddWithValue("#Hobby", comboBox1.Text);
again.Connection = test;
test.Open();
again.ExecuteNonQuery();
test.Close();
MessageBox.Show("Data Entry Successful");
}
}
}
catch (Exception ex)
{
throw ex;
}
}
Check whether it is working or not. Hope atleast it will give you one step ahead result to let you know if any exception arises
Precisely this exception is being thrown because table is a reserved keyword. SQL engine encounters this reserved keyword, when it expects to find a proper name of the table and thus throws an exception. Try specifiying correct table name, because I believe this table name was given just as an example.
Your statement should look a little bit more like this
INSERT INTO MyTable Values ...
Other answers about using parametrized query in incorrect way are also valid.
there are 3 issues in your code.
1) you have reserved keyword for table name, Table
2) SQL query you are building from code is incorrect.
3) You need to specify your command type.
Solution: Change table name to something meaningful, like employeedata or testdata and modify your code according to given below.
again.CommandType = CommandType.Text;
again.CommandText = "INSERT INTO TestData(ColumnName1,ColumnName2) Values('" + textBox1.Text + "', '" + comboBox1.Text + "')";
again.Connection = test;
test.Open();
again.ExecuteNonQuery();
test.Close();
MessageBox.Show("Data Entry Successful");
This is my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace SDD_Single_Project___Michael_Merjane
{
public partial class NewUser : Form
{
private OleDbConnection connection = new OleDbConnection(); //setting up a private connection
public NewUser()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\schoolwork\Year 11\SDD\3 SINGLE TASK\SDD Single Project - Michael Merjane\SDD Single Project - Michael Merjane\bin\Persondata.accdb; //PROBLEM IS HERE
Persist Security Info=False;"; // there is no security for finding the location, this is not very safe but for the circumstances it works. In the line above, it is finding the location of the database. This could change due to computer and cause the whole program to not run
}
private void btnBack_Click(object sender, EventArgs e) //all of these mean when button is clicked
{
this.Hide(); //hides this page
MainScreen frm = new MainScreen(); //finds the next screen (the main screen)
frm.Show(); //shows it
}
private void btnSubmit_Click(object sender, EventArgs e)
{
try {
connection.Open(); // opens the connection
OleDbCommand command = new OleDbCommand(); //names command as a new oledbcommand for further use
command.Connection = connection;
command.CommandText = "insert into Persondata ( FirstName,LastName,Address,Suburb,Email,Mobile,Gender,Age) values ( '" + txtFirst.Text + "' , '" + txtLast.Text + "' , '" + txtAddress.Text + "' , '" + txtSuburb.Text + "' , '" + txtEmail.Text + "' , '" + txtMobile.Text + "' , '" + dropGender.Text + "' , '" + dropAge.Text + "') ";
// finds where its going to, finds the columns it is going to fill, finds the text boxes that is going to fill them
command.ExecuteNonQuery(); //execute the save
MessageBox.Show("Data Saved"); //pretty much shows a box saying everything worked
connection.Close(); // closes the connection
}
catch (Exception ex) //if something has gone wrong a catch will occur
{
MessageBox.Show("Error " + ex); //show the error
} //if there is a error message box will appear informing it
}
}
}
This is code for an assignment I must give in, the problem is I won't be able to hand it because then the absolute path won't find the file. I need a way to use a relative file path that can change due to a change in location. At the moment, the path (as long is it is) goes to the bin folder within the programs files. So if there was a way to change it so it somehow automatically looks in its own program files to the bin or anywhere else in its own program files that would be great.
Put whatever file you want into the folder your current ptoject is. Then
Directory.GetCurrentDirectory()
will give the current folder you are working on. It will give you the release folder of your project. Store it as a string and use it where ever needed.
try :
var currDir = System.Environment.CurrentDirectory;
then concatenate the path from there...
Sure.
That is pretty basic thing - I'd suggest putting database file in DB folder inside bin - or left inside bin as it is.
Then you need to determine location of your binary folder - there are several ways, while two below are most common:
Environment.CurrentDirectory - will work until you are not changing it during run-time (elsewhere)
Assembly.GetEntryAssembly().Location - which is full path to the executable that started current process
I'd suggest then looking onto System.IO.Path class - first to strip only path from Location and then to combine it back but this time with database file-name string.
While this is you assignment I'm going to leave you here to study this class by yourself - this is pretty interesting one :P
http://msdn.microsoft.com/en-us/library/system.io.path(v=vs.110).aspx
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have a very simple Windows Form. I want to add data to a database by using it.
In my C# winforms solution, I created a data source named db_studentDataSet and connected my database db_student. Whenever I run my solution, I get the following exception:
SqlException was unhandled: Login failed for user 'sa'
Here's my code:
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SimpleEnrollmentSystem
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void buttonAdd_Click(object sender, EventArgs e)
{
this.Validate();
this.studentsBindingSource.EndEdit();
studentsTableAdapter.Insert("Ahmed", "Rownak", "Male", 13, "Malibagh");
}
}
}
Here's a image of my form:
Here's my database:
CREATE TABLE Students
(
StudentID int primary key,
FirstName string,
LastName string,
Gender string,
Age int,
Address string
)
Note that I've only coded for the Add button functionality.
What is wrong with my code? Or is it anything else? Maybe the way I'm trying to achieve this is wrong? Is there a better way, in that case?
I'm using Visual Studio 2012 Ultimate and SQL Server 2012 Express Edition.
EDIT - 1: I have changed my buttonAdd_Click() method.
private void buttonAdd_Click(object sender, EventArgs e)
{
SqlConnection con1 = new SqlConnection("Data Source=SAADMAAN;Initial Catalog=db_student;User ID=sa;Password=***********");
con1.Open();
SqlCommand cmd1 = new SqlCommand("INSERT INTO Students(StudentID, FirstName, LastName, Gender, Age, Address) VALUES('" + studentIDTextBox.Text + "','" + firstNameTextBox.Text + "','" + lastNameTextBox.Text + "','" + genderTextBox.Text + "','" + ageTextBox.Text + "','" + addressTextBox.Text +"')",con1);
cmd1.ExecuteNonQuery();
con1.Close();
}
According to user Kiran Hegde's suggestion, I changed the password into clear text in my connection string.
SqlConnection con1 = new SqlConnection("Data Source=SAADMAAN;Initial Catalog=db_student;User ID=sa;Password=open");
That solved the problem. So silly of me, I skipped this obvious thing.
I know I have done this a few times before but for the life of me can't remember how.
I have a database I have created and I want to make a software that only inputs information into the database. The program works but my sql connection is the problem. So to test it out I basically tried to do it direct inserting hard-coded info but it still will not go. where am I going wrong?:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data.Sql;
namespace InventoryTracker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static void CreateCommand()
{
SqlConnection myConnection = new SqlConnection("User Id=Jab" + "password=''" + "Data Source=localhost;" + "Trusted_Connection=yes;" + "database=InventoryTracker;" + "Table=Inventory;");
try
{
myConnection.Open();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
SqlCommand myCommand = new SqlCommand("INSERT INTO Inventory (ItemName, SerialNumber, Model, Department, Quantity, Notes) " + "Values (string,string,string,string, 1, string)", myConnection);
}
}
}
Thank you in advance! :-)
Your sql connection string is messed up, you need semi-colons between all parameters and your parameters are messed up too. I.e., something like
"Server=localhost;Database=InventoryTracker;Trusted_Connection=True;"
You are mixing trusted mode and specifying the user id -- trusted connection means to use your windows login credentials.
TableName does not go in the connection string.
This site is great for connection string examples http://www.connectionstrings.com/sql-server-2008
You SQL command, "INSERT INTO Inventory (ItemName ..." is pretty messed up too. Should be something like
INSERT INTO Inventory (ItemName ...) values(#ItemName ...)
You then pass in the values like
myCommand.Parameters.Add("ItemName", SqlType.VarChar).Value = "Dozen Eggs";
See Insert data into SQL Server from C# code for a simple example
Just use the SqlConnectionStringBuilder class.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.aspx
Instead of:
"User Id=Jab" + "password=''" + "Data Source=localhost;" + "Trusted_Connection=yes;" + "database=InventoryTracker;" + "Table=Inventory;");
Try:
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.UserID = "Jab";
builder.Password = "";
builder.DataSource = "localhost";
builder.InitialCatalog = "InventoryTracker";
// Don't put table name in your connection string
string connection_str = "Data Source = localhost ; uid = db_user; pwd = db_pass; database = db_name; ";
conn = new SqlConnection(connection_str);
conn.Open();
Try changing
"User Id=Jab" + "password=''" + "Data Source=localhost;" + "Trusted_Connection=yes;" + "database=InventoryTracker;" + "Table=Inventory;"
to
"User Id=Jab; " + "Password=''; " + "Data Source=localhost; " + "Trusted_Connection=yes; " + "Initial Catalog=InventoryTracker;"
(Changed upper/lower case, "Database" to "Initial Catalog", removed "Table" and added ";")
Also, you might want to try replacing "Data Source" by "Server".
Don't forget to call myCommand.ExecuteNonQuery to get it to actually execute your query. Without this, you are just creating a command, but not running it.
First off, I'd like to say that this is the most brilliant forum I've encountered in my programming journey, and I've been google-fishing for all the help I can get for the last three months. Great support, and even greater style #necromancer badge.
Enough with the flattery.
I'm doing a practice project, insurance website. Right now, I need to get user input from the textboxes into the database. I have seen plenty of related questions here, but I'm getting an error message on my connection I haven't found on any of the other posts, and I'm so ignorant it's difficult to apply examples that don't fit exactly what I'm doing. (As a side note, my trainer specifically wants the most basic form of this code, and as such told me not to worry about parameterizing the queries for security or to use a try-catch block for exceptions, but many thanks to the answers here for those pointers)
The error message I get is "Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed."
Am I getting my syntax wrong? Am I using the 'TextBox1.Text' value right? Am I just too stupid to be doing this?
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class SubmissionPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
String connectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\aspnetdb.mdf;Integrated Security=True;User Instance=True";
SqlConnection sqlConn = new SqlConnection(connectionString);
sqlConn.Open();
String thisQuery = "INSERT INTO Customer (" + " Name, SIC_NAIC, Address, City, State, Zip, " + ") VALUES (" + " #TextBox1.Text, #RadioButtonList1.SelecedItem, #TextBox2.Text, #DropDownList1.SelectedItem, #TextBox3.Text" + ")";
SqlCommand thisCommand = new SqlCommand(thisQuery, sqlConn);
thisCommand.ExecuteNonQuery();
sqlConn.Close();
}
}
Check this and use sql parameters:
using (var conn = new SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=aspnetdb;Integrated Security=True;Connect Timeout=30;User Instance=True"))
{
conn.Open();
using (var cmd = new SqlCommand("INSERT INTO Customer (Name,SIC_NAIC) VALUES (#Name,#SIC_NAIC)",conn))
{
try
{
cmd.Parameters.Add("#Name", SQlDbType.VarChar, 50).Value = TextBox1.Text;
cmd.Parameters.Add("#SIC_NAIC", SQlDbType.VarChar, 50).Value = RadioButtonList1.SelecedItem.ToString();
cmd.ExecuteNonQuery();
}
catch (Exception)
{
{
}
throw;
}
finally
{
if (conn.State == ConnectionState.Open) conn.Close();
}
}
Make sure you have downloaded sqlmanagement studio 2008 express.. and then attach asp.netdb on it and change your sql connectionstring.
sql ms
Regards
This error is often caused because the parent instance (for whatever reason) can't copy the system databases to the users local isolated storage folders. Sometimes it is because of a previous install of SQL Express has left files in that directory. Full story here
http://social.msdn.microsoft.com/Forums/en/sqldatabaseengine/thread/f5eb164d-9774-4864-ae05-cac99740949b
could be due to permission issue, check eventlog. you may try removing User Instance=True from connection string
In addition to answers regarding SQL database instances, your SQL query looks wrong. Try changing your embedded query to:
String thisQuery = "INSERT INTO Customer (Name, SIC_NAIC, Address, City, State, Zip) VALUES ('" + TextBox1.Text + "', '" + RadioButtonList1.SelecedItem.Text + "', '" + TextBox2.Text + "', '" + DropDownList1.SelectedItem.Text + "', '" + TextBox3.Text + "', '" + TextBoxZip.Text + "')";
This will format the SQL statement from the values on your form.
NOTE: Assuming field SIC_NAIC and State are storing text values and an additional field for Zip (TextBoxZip).
First of all, if your mdf resides at App_Data, then your connection string is all wrong.
Put the following in your web.config
<connectionStrings>
<add name="MyConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\aspnetdb.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
Now call it like
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
Here is a fix for your error. But you should have an instance of SQL Express installed, which I supposecomes standard with Visual Studio.
http://www.aspdotnetfaq.com/Faq/fix-error-Failed-to-generate-a-user-instance-of-SQL-Server-due-to-a-failure-in-starting-the-process-for-the-user-instance.aspx
And while you are at it, please alter your Button_Click event like this
protected void Button1_Click(object sender, EventArgs e)
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
string sql = "INSERT INTO Customer (Name, SIC_NAIC, Address, City, State, Zip) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}')";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = String.Format(sql,
TextBox1.Text,
RadioButtonList1.SelectedItem.Text,
TextBox2.Text,
DropDownList1.SelectedItem.Text,
TextBox3.Text,
"000000");
using (SqlCommand command = new SqlCommand(query, connection))
{
command.ExecuteNonQuery();
}
}
}
Also keep in mind that you cannot insert RadioButtonList1.SelecedItem or DropDownList1.SelectedItem to database. You must append either .Text or .Value to it as per your requirement.
Ok guys, first of all I'm overwhelmed by the helpfulness I found here. I'll be a stackoverflow-er for life. Thank you all for taking your time and experience to aid a total stranger. I couldn't have gotten this done without it.
I wanted to post the code I ended up with, just so as to have a record of what actually worked for me in case someone with the same issue needs to see the end result. As per #yetanothercoder's recommendation, I placed this connection string in my webconfig file, and it looked like this (from ?xml version... to configuration is just to show where I placed the code, since I had wondered about that myself, the connection string is wrapped between the tags):
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="MyConnectionString" connectionString="Data Source=The-Crushinator\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ArgonautSubmission.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
And, although my trainer assured me that the using block #yetanothercoder suggested should be fine, it wasn't working for me, so I used the example from #chaps' answer, remembering to put in the TextBox4.Text value forgot. The code looks like this:
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class SubmissionPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
String thisQuery = "INSERT INTO Customer (Name, SIC_NAIC, Address, City, State, Zip) VALUES ('" + TextBox1.Text + "', '" + RadioButtonList1.SelectedItem.Text + "', '" + TextBox2.Text + "', '" + TextBox3.Text + "', '" + DropDownList1.SelectedItem.Text + "', '" + TextBox4.Text + "')";
using (SqlConnection sqlConn = new SqlConnection(connectionString))
{
sqlConn.Open();
using (SqlCommand command = new SqlCommand(thisQuery, sqlConn))
{
command.ExecuteNonQuery();
}
}
}
}
Next came the more convoluted part. To rid myself of the dreaded "Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed" error message, I followed this link from #yetanother coder,
and found that I needed to install Sql Server Management Studio Express. I had to use Microsoft Web Platform Installer because when I tried to follow the instructions at msdn.com for downloading ssmse, I kept getting a cyclical error. I installed ssmse, opened up the query window with the 'new query' button, and executed this command
exec sp_configure 'user instances enabled', 1.
Go
Reconfigure
then I restarted sql server, added a new database to my asp.net project, and BAM! It worked! User info was saved into the database, where it was supposed to go! I had been so conditioned to expecting failure from my code that it felt like watching my first rocket make it into orbit. Awesome. Thanks again, everyone, and I hope this helps someone in a similar situation.