2011-04-21 23 views
1

我已經具有複選框模板字段一個gridview,我使用C#代碼和基本上,當用戶檢查所有的Checkboxs在數據網格視圖我要添加這些值轉換成數據類型爲Bit的SQL數據庫。 這是我的代碼到目前爲止;從複選框模板字段插入值到SQL數據庫字段類型位

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", AttendanceCheckBox); 

如何將複選框控件的值傳遞到數據類型爲Bit的sql數據庫字段?任何幫助表示感謝,提前致謝!

回答

1

的所有下面的代碼首先將引發一個空引用異常,如果沒有找到該複選框(例如,如果它是一個頁眉/頁腳)。

if (((CheckBox)row.FindControl("AttendanceCheckBox")).Checked) 

可以存儲在位字段中的唯一值是1或0,而複選框的「值」是文本。您是否真的想根據該值選擇要保存的字段,然後根據是否選中該複選框來選擇要保存的值?請詳細說明。

而且您更新嘗試下面的代碼:

foreach (GridViewRow row in GridView2.Rows) 
    { 
    CheckBox AttendanceCheckBox = row.FindControl("AttendanceCheckBox") as CheckBox; 
    if (AttendanceCheckBox != null) 
    { 
     try 
     {     
      connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["RegisterConnectionString"].ConnectionString); 
      SqlCommand command = new SqlCommand("INSERT INTO Attendance(Present, StudentID, LessonID) VALUES(@AttendanceChecked, @StudentID, @LessonID)"); 
      command.Parameters.AddWithValue("@AttendanceCheck",AttendanceCheckBox.Checked); 

您還需要添加@StudentID的值,並使用相同的方法command.Parameters.AddWithValue @LessonID。

+0

對不起,我的意思是,當複選框被選中我想保存1中的數據類型字段位,而當它未被選中我想在數據類型字段保存位0。謝謝你的幫助! – user715115 2011-04-21 12:41:41

相關問題