[英]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.