2014-12-04 60 views
-1

我工作的Windows窗體有一個CheckedListBox控件(cbIntendedMajor),我試圖插入到Access數據庫中。我沒有返回任何錯誤,但是當我選擇多個複選框項目時,只有第一個選定的項目用逗號插入到表格中。任何關於我在這裏失蹤的指針?以下是我的代碼:Visual Studio - Windows窗體 - CheckedListBox插入不正確。 C#

private void button1_Click(object sender, EventArgs e) 
    { 
     string conString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Temp\Interest.accdb"; 
     OleDbConnection con = new OleDbConnection(conString); 
     OleDbCommand cmd = con.CreateCommand(); 
     string text = "INSERT INTO InterestCard (FirstName, LastName, StreetAddress, City, State, ZipCode, Phone, Email, DOB, Gender, HighSchool, GraduationYear, PlannedTerm, IntendedMajor) VALUES (@FName, @LName, @SAddress, @City, @State, @Zip, @Phone, @Email, @DOB, @Gender, @HSchool, @GradYear, @PTerm, @IMajor)"; 
     cmd.CommandText = text; 

      con.Open(); 
      cmd.Parameters.AddWithValue("@FName", txtFirstName.Text); 
      cmd.Parameters.AddWithValue("@LName", txtLastName.Text); 
      cmd.Parameters.AddWithValue("@SAddress", txtAddress.Text); 
      cmd.Parameters.AddWithValue("@City", txtCity.Text); 
      cmd.Parameters.AddWithValue("@State", txtState.Text); 
      cmd.Parameters.AddWithValue("@Zip", txtZipCode.Text); 
      cmd.Parameters.AddWithValue("@Phone", txtPhone.Text); 
      cmd.Parameters.AddWithValue("@Email", txtEmail.Text); 
      cmd.Parameters.AddWithValue("@DOB", dtpDOB.Value); 
      cmd.Parameters.AddWithValue("@Gender", rbFemale.Checked); 
      cmd.Parameters.AddWithValue("@HSchool", txtHighSchool.Text); 
      cmd.Parameters.AddWithValue("@GradYear", txtGraduationYear.Text); 
      cmd.Parameters.AddWithValue("@PTerm", txtTermofEnrollment.Text); 




      foreach (string s in cbIntendedMajor.CheckedItems) 
      { 

        cmd.Parameters.AddWithValue("@IMajor", s + ","); 

      } 


      cmd.ExecuteNonQuery(); 


    } 
+0

你反覆調用AddWithValue(「@ IMajor」),只有最後一個會有效果。首先創建字符串, *然後*調用AddWithValue – 2014-12-04 16:54:53

+0

這是有道理的,我甚至沒有注意到我在循環中添加,謝謝。 – user1863593 2014-12-04 16:57:38

回答

0

我認爲你的參數只能添加一次。你也許會考慮迭代.CheckedItems,創建一個單一的字符串,每個項目用逗號加上。然後在foreach()循環外部,你可以cmd.Parameters.AddwithValue(「@ IMajor」,fullString

相關問題