Asp.Net使用文本框插入数据到数据库 [英] Asp.Net inserting data into a database using a textbox

查看:139
本文介绍了Asp.Net使用文本框插入数据到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的网站上,当填完后我收到一封电子邮件,说有人已经签署了,但我还需要将数据存储到一个SQL数据库的电子邮件注册表格。我创建了与表单上的字段相匹配的SQL数据库。如何将我得到的第一个名称字段:

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>

进入我的数据库我的名字字段? (我在C#这样一来,使用Visual Studio 2013,Web Forms和使用SQL 2012前preSS)

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

我已经与数据库所做的唯一工作是使用gridvieww和细节视图控件。该网站有没有数据库连接呢。

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

感谢

推荐答案

试试这个:

在codebehind:

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();

还记得使用可以通过rightclicking用蓝色下划线的项目中添加合适的命名空间,然后单击解决。

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

您也需要在这样的Web.config文件来定义你的ConnectionString:

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>

这篇关于Asp.Net使用文本框插入数据到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆