ASP.net using a form to insert data into an sql server table

后端 未结 2 1713
悲&欢浪女
悲&欢浪女 2021-02-04 04:26

Hi in php i would do a form with an action to lets say a process.php page and in that page i would take the post values and using a mysql_query would do an insertion. now i am l

2条回答
  •  孤城傲影
    2021-02-04 04:45

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

    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:

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

    
    

    define a button to process your logic like so (notice the onclick):

    
    

    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.

    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 
              }
       }
    }
    

提交回复
热议问题