2016-03-30 12 views
0

ボタンを1回クリックしてデータを挿入する場合は、ドロップダウンリストの選択番号と2つのテキストボックスがあります。私はドロップダウンリスト番号[ex。 2]を入力し、2つのテキストボックスに入力データを入力し、[挿入]ボタンを1回クリックします。データは複数の行のデータベーステーブルに保存され、ドロップダウンリストからいくつの番号を選択しますか。例えば、データを動的に複数の行に1つのボタンをクリックして挿入

dropdown-list = 0,1,2,3,4; //データベーステーブルに複数の行を挿入する任意の数を選択します。

[1] textbox = "data"; //入力データ
[2] textbox = "data"; //入力データ

[ボタンクリック]

マイコード:

protected void Button1_Click(object sender, EventArgs e) 
{ 
    con = new SqlConnection(); 
    con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString(); 
    string value = DropDownList4.SelectedValue.ToString(); // Get the dropdown value 
    int count = 0; 
    int.TryParse(value, out count); // cast the value to integer 
    for (int i = 0; i < count; i++) // iterate it for the N times 
    { 
     SqlCommand insert = new SqlCommand("insert into Test(Name, Username) values(@Name, @Username)", con); 
     insert.Parameters.AddWithValue("@Name", TextBox1.Text); 
     insert.Parameters.AddWithValue("@Username", TextBox2.Text); 
     try 
     { 
      con.Open(); 
      insert.ExecuteNonQuery(); 
     } 
     catch 
     { 
      con.Close(); 
     } 
    } 
    GridView1.DataBind(); 
} 

- このコードは、データベース内のデータを正しく挿入することはできません。 dropdwn-listの値3を選択すると、行が2回挿入されます。 5を選択すると、3回挿入されます。何が必要な変更が必要な助けてください。 thnx

+0

これはwpfまたはwinformsアプリケーションですか? DropDownListにValuePathとDisplayPathを設定しましたか? – schlonzo

+0

'i <= count'の意味 –

+0

データベースに同じ行を1回以上挿入するのは間違いです。データベース表の行は一意でなければなりません。 –

答えて

3

あなたは接続ブロックを閉じているだけです。 これが起こります。 が挿入されていますが、接続が閉じられていません.2回目の反復例外が発生し、接続が閉じられています。 3回目の反復値が再び挿入されます。 ここに更新コードがあります

protected void Button1_Click(object sender, EventArgs e) 
    { 
     con = new SqlConnection(); 
     con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString(); 

     string value = DropDownList4.SelectedValue.ToString(); // Get the dropdown value 
     int count = 0; 
     int.TryParse(value, out count); // cast the value to integer 

     for (int i = 0; i < count; i++) // iterate it for the N times 
     { 

      SqlCommand insert = new SqlCommand("insert into Test(Name, Username) values(@Name, @Username)", con); 
      insert.Parameters.AddWithValue("@Name", TextBox1.Text); 
      insert.Parameters.AddWithValue("@Username", TextBox2.Text); 

      try 
      { 
       con.Open(); 
       insert.ExecuteNonQuery(); 

      } 
      catch 
      { 
       i--; 
      } 
      finally 
      { 
       con.Close(); 
      }  
     } 
     GridView1.DataBind(); 

    } 
+0

thnx thnx thnx .............................. @ M.Sheraz Leo – Shrv11

+0

私はあなたを助けることができてうれしいです: )あなたの問題を解決したら答えを受け入れてください –

関連する問題