![](/img/trans.png)
[英]How to insert 1 or 0 in Sql Server for bit type field if checkbox is checked?
[英]Inserting value from Checkbox Template Field into sql database field type Bit
我有一個帶有Checkbox Template字段的gridview,我正在使用C#代碼,並且基本上,當用戶在datagrid視圖中選中所有Checkbox時,我想將這些值添加到具有數據類型字段Bit的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數據庫字段中? 任何幫助表示贊賞,在此先感謝!
首先,以下代碼如果未找到復選框(例如,如果是頁眉/頁腳),則將引發空引用異常。
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);
您還需要使用相同的command.Parameters.AddWithValue
方法添加@StudentID和@LessonID的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.