且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.net使用表单将数据插入到一个SQL Server表

更新时间:2023-01-29 10:11:29

有吨样品code网上至于如何做到这一点。

There are tons of sample code online as to how to do this.

下面是如何做到这一点只是一个例子:
http://geekswithblogs.net/dotNETvinz/archive/2009/04/30/creating-a-simple-registration-form-in-asp.net.aspx

Here is just one example of how to do this: http://geekswithblogs.net/dotNETvinz/archive/2009/04/30/creating-a-simple-registration-form-in-asp.net.aspx

定义了以下标签之间的文本框:

you define the text boxes between the following tag:

<form id="form1" runat="server"> 

您创建文本框,并定义它们=服务器,像这样:

you create your textboxes and define them to runat="server" like so:

<asp:TextBox ID="TxtName" runat="server"></asp:TextBox>

定义一个按钮来处理你的逻辑,像这样(注意的onclick

<asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />

在code的后面,可以定义你想要的服务器做的,如果用户定义了一个名为方法点击按钮

in the code behind, you define what you want the server to do if the user clicks on the button by defining a method named

protected void Button1_Click(object sender, EventArgs e)

或者你可以只需双击在设计视图中的按钮。

or you could just double click the button in the design view.

下面是code的一个非常快速的样品插入在按钮单击事件表(codebehind)

Here is a very quick sample of code to insert into a table in the button click event (codebehind)

protected void Button1_Click(object sender, EventArgs e)
{
   string name = TxtName.Text; // Scrub user data

   string connString = ConfigurationManager.ConnectionStrings["yourconnstringInWebConfig"].ConnectionString;
   SqlConnection conn = null;
   try
   {
          conn = new SqlConnection(connString);
          conn.Open();

          using(SqlCommand cmd = new SqlCommand())
          {
                 cmd.Conn = conn;
                 cmd.CommandType = CommandType.Text;
                 cmd.CommandText = "INSERT INTO dummyTable(name) Values (@var)";
                 cmd.Parameters.AddWithValue("@var", name);
                 int rowsAffected = cmd.ExecuteNonQuery();
                 if(rowsAffected ==1)
                 {
                        //Success notification
                 }
                 else
                 {
                        //Error notification
                 }
          }
   }
   catch(Exception ex)
   {
          //log error 
          //display friendly error to user
   }
   finally
   {
          if(conn!=null)
          {
                 //cleanup connection i.e close 
          }
   }
}