下面的代碼是我的代碼示例如何連接和添加文本框我現在想要的是如何添加與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();
}
「添加一個下拉列表」?這是什麼意思 –
通過下拉列表給數據庫添加新的值 –
@William:我不明白你的問題,但是你的代碼存在錯誤。您應該始終檢查IsPostback,並且只綁定if(!IsPostback){...} – TCM