简体   繁体   中英

Asp.Net inserting data into a database using a textbox

I have an email signup form on my site, when the form is completed I get an email saying somebody has signed up but I also need to store the data into a Sql database. I've created an sql database that matches up with the fields on the form. How would I get the first name field:

  <asp:TextBox ID="txtFname" runat="server" placeholder="First Name"></asp:TextBox>

Into my firstName field in my database? (I'm doing this in c#,using Visual Studio 2013, Web Forms and using SQL 2012 Express)

The only work I've done with databases is using the gridvieww and details view controls. The site has no database connections yet.

Thanks

Try this:

In codebehind:

//Makes a variable that contains your textbox value
string FirstName = TxtFname.Text;

//Inserts the FirstName variable into the db-table
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
        SqlCommand cmd = new SqlCommand();

        cmd.CommandText = "INSERT INTO YourTableName (YourFirstNameColumnName) VALUES (@FirstName)

        //Uses the FirstName variable and creates a new sql variable for use in the sql commandtext
        cmd.Parameters.Add("@FirstName", SqlDbType.NVarChar).Value = FirstName;

        cmd.Connection = conn;

        conn.Open();

        cmd.ExecuteNonQuery();

        conn.Close();

Also remember to use the right namespaces which can be added by rightclicking the items with blue underline, and click "resolve".

You will also need to define your connectionstring in the Web.config file like this:

<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <add name="ConnectionString" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>
</configuration>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM