아래의 코드는 코드 예제입니다. 텍스트 상자를 사용하여 연결하고 추가하는 방법은 dropdownlist를 추가하는 방법입니다. 코드 샘플 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();
}
"드롭 다운 목록으로 추가 하시겠습니까?" 의미는 무엇입니까 –
dropdownlist에 의해 데이터베이스에 새 값 추가 –
@ 윌리엄 : 귀하의 질문에 이해가되지 않지만 코드에 실수가 있습니다. IsPostback을 확인하고 if (! IsPostback) {...}의 gridview 만 바인딩해야합니다. – TCM