2012-10-10 76 views
0

下面的代码是我的代码示例如何连接和添加文本框我现在想要的是如何添加与dropdownlist ...代码示例如何通过下拉列表添加人请???C#asp.net SQL如何通过dropdownlist将新值添加到数据库?

public partial class SQL_Test : System.Web.UI.Page 
    { 
     SqlConnection myConnection; 
     DataSet dataSet; 
     string sql; 
     SqlDataAdapter dataAdapter; 
     protected void Page_Load(object sender, EventArgs e) 
     { 
      myConnection = new SqlConnection("trusted_connection=yes;" + "database=DataBaseConnection;" + "connection timeout=30;"); 
      dataSet = new DataSet(); 
      sql = "SELECT Firstname,Surname FROM BasicInfo"; 
      dataAdapter = new SqlDataAdapter(sql, myConnection); 
      //fill dataset 
      dataAdapter.Fill(dataSet, "datafill"); 

      //bind database to gridviwe 
      GridView1.DataSource = dataSet; 
      GridView1.DataBind(); 
     } 
     protected void Button1_Click(object sender, EventArgs e) 
     { 
      myConnection.Open(); 
      SqlCommand AddCommand = new SqlCommand("INSERT INTO BasicInfo (Firstname,Surname) values(@a,@b)", myConnection); 

      if (TextBox1.Text != null && TextBox2.Text != null) 
      { 
       //TextBox set Parameters 
       AddCommand.Parameters.AddWithValue("@a", TextBox1.Text); 
       AddCommand.Parameters.AddWithValue("@b", TextBox2.Text); 

       //Execute Query 
       AddCommand.ExecuteNonQuery(); 

       //emptied textbox's 
       TextBox1.Text = ""; 
       TextBox1.Text = ""; 

       //Redirect 
       Response.Redirect("SQL-Test.aspx"); 
      } 

      //close connection 
      myConnection.Close(); 
     } 
+0

“添加一个下拉列表”?这是什么意思 –

+0

通过下拉列表给数据库添加新的值 –

+0

@William:我不明白你的问题,但是你的代码存在错误。您应该始终检查IsPostback,并且只绑定if(!IsPostback){...} – TCM

回答

1

要从下拉列表中获取所选值,您可以访问Text属性。

AddCommand.Parameters.AddWithValue("@a", TextBox1.Text); 
AddCommand.Parameters.AddWithValue("@d", DropDownList1.Text); 
+0

非常感谢你的麻烦:( –

1

你试图通过下拉列表来SQL命令所选择的价值?如果是这样,你可以使用 AddCommand.Parameters.AddWithValue(“@ a”,Dropdownlist.SelectedValue);或 AddCommand.Parameters.AddWithValue(“@ a”,Dropdownlist.SelectedText);

+0

非常感谢你的帮助,我忘了它,所以很抱歉给我带来麻烦。 –

相关问题