2011-04-21 45 views
0

我有一個GridView的複選框模板字段,我使用C#代碼,基本上當用戶檢查DataGrid視圖中的所有複選框我想根據複選框被選中或不選中,將1或0添加到具有數據類型字段位的SQL數據庫中。這是我的代碼到目前爲止;插入1或0在基於GridView中選中的複選框的sqlDatabase

protected void SaveRegisterButton_Click(object sender, EventArgs e) 
{ 
      SqlConnection connection; 
      SqlCommand command; 
      int numRowsAdded; 
      int id; 
      //Boolean AttendanceChecked; 
    foreach (GridViewRow row in GridView2.Rows) 
    { 
     if (((CheckBox)row.FindControl("AttendanceCheckBox")).Checked) 
     { 


      try 
      { 
       // Connecting to the database using the connection string in the web.config file 
       connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["RegisterConnectionString"].ConnectionString); 

       // Create an INSERT Sql statement 
       // To prevent an Sql injection attack, we add parameters with names starting with an @ symbol 
       command = new SqlCommand("INSERT INTO Attendance(Present, StudentID, LessonID) VALUES(@AttendanceChecked, @StudentID, @LessonID)", 


       // Replace the parameters with the actual values read from the form 
       //command.Parameters.AddWithValue("@AttendanceChecked", SqlDbType.Bit).Value = AttendanceChecked; 
       //command.Parameters.AddWithValue("@AttendanceChecked", CheckBox("Attend 
       //com.Parameters.Add("@Approved", SqlDbType.Bit).Value = status; 

我正在努力實現我的項目的這一部分,任何幫助將不勝感激!在此先感謝...

+0

究竟是什麼,你有問題?哪一部分? – Oded 2011-04-21 13:09:09

+0

向數據庫的位域添加'true'(1)或'false(0)'。基於複選框被選中,我該如何實現這一點? – user715115 2011-04-21 13:10:35

+0

選中的複選框將對應於「真」。如果選中,則向數據庫插入1,否則爲0.我仍然不知道您遇到問題的位置。 – Oded 2011-04-21 13:12:46

回答

0

試試這個:

command.Parameters["@AttendanceChecked"].Value = AttendanceChecked ? 1 : 0; 
+0

這不工作...錯誤消息說不能將'對象'轉換爲'System.Data.SqlClient.SqlConnection?我的代碼到目前爲止檢查gridview中的每一行,然後找到gridview中的複選框,如果複選框被選中,那麼我想在Bit數據庫字段中加1。謝謝 – user715115 2011-04-21 13:23:33

+0

世界上的哪個地方在'SqlConnection?爲什麼要使它可以爲空(如果這確實是你想說的話)? – 2011-04-21 13:47:49

+0

@user:從粘貼的內容來看,我會說你需要粘貼整個方法,而不僅僅是那一部分。 – hyp 2011-04-21 14:13:07

相關問題