【发布时间】:2017-06-29 19:23:20
【问题描述】:
所以我有这个DataGridView,其中有两列我从我的SQL Server 数据库中检索。现在,在第二列中,我们有一个位字段,在我的 Windows 应用程序设计器中显示为 CheckBox。所以,我想在CellContentClick 事件上更新刚刚被取消选择到我的数据库中的值。但似乎我无处可去。
下面是我的代码:
private void gvTurnOffNotifications_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
foreach (DataGridViewRow row in gvTurnOffNotifications.Rows)
{
DataGridViewCheckBoxCell cell = row.Cells[1] as DataGridViewCheckBoxCell;
//We don't want a null exception!
if (cell.Value != null)
{
bool result = Convert.ToBoolean(row.Cells[1].Value);
if (result == true)
{
//It's checked!
btnUpdateTurnOff.Enabled = true;
myConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (mySQLConnection = new SqlConnection(myConnectionString))
{
int temp = 1;
bool change = false;
string procedureName = "update UsersNotified Set AllowNotification='" + change + "' where AllowNotification='" + false+ "'";
mySQLCommand = new SqlCommand(procedureName, mySQLConnection);
mySQLCommand.CommandType = CommandType.Text;
mySQLCommand.Connection = mySQLConnection;
mySQLCommand.Connection.Open();
mySQLCommand.ExecuteNonQuery();
}
}
}
}
}
然后当我点击“更新”按钮时,我想发送更新的网格数据以存储在我的数据库中,如下所示:
private void btnUpdateTurnOff_Click(object sender, EventArgs e)
{
myConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (mySQLConnection = new SqlConnection(myConnectionString))
{
mySQLDataAdapter = new SqlDataAdapter("spGetAllUpdatedNotifications", mySQLConnection);
mySQLDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;
mySQLCommand.Connection = mySQLConnection;
mySQLCommand.Connection.Open();
DataSet ds = new DataSet();
mySQLDataAdapter.Fill(ds);
mySQLDataAdapter.UpdateCommand = mySQLCommand;
mySQLDataAdapter.Update(ds);
}
}
我的更新块中的spGetAllUpdatedNotifications 对象是一个存储过程,我调用它只是为了从数据库中检索记录,以便我可以在我的DataSet 中即时更新它们。下面是定义:
create proc spGetAllUpdatedNotifications
as
begin
SELECT UserName, AllowNotification FROM UsersNotified where AllowNotification=1
end
GO
更多上下文:当我的表单加载时,我从数据库中选择其 AllowNotification 字段设置为第 1 位(在 C# 中为 true)的所有记录,并且一旦用户取消选中特定用户(换句话说,该用户将不再被允许接收通知)并且一旦我单击更新按钮,它应该将属性设置为 false(数据库中的位 0)。
它不会更新我取消选择的一条记录,而是更新所有记录。在这种情况下,“全部”是具有AllowNotification=1 的记录。我只想为取消选中/未选中的记录设置AllowNotification=0only
关于如何实现这一目标的任何建议?
【问题讨论】:
-
当前代码遇到什么问题?
-
不是更新我取消选择的一条记录,而是更新所有记录。在这种情况下,“全部”是具有
AllowNotification=1的记录。我只想为取消选择/未选中的记录设置 AllowNotification=0`。 -
因为更新查询中没有 where 子句。
-
它就在那里。请再检查一次。只是
where子句是错误的。这就是问题所在。这是一个我无法理解的逻辑错误 -
您的 where 子句不正确。根据您的查询,
AllowNotification=false的所有行都将更新为 true。您需要在 where 子句中添加一个条件,该条件可以识别您要更新的单个记录,例如用户 ID 或其他内容。
标签: c# sql sql-server