【问题标题】:Update DataGridView Checked Record to the Database将 DataGridView 检查记录更新到数据库
【发布时间】: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


【解决方案1】:

我不确定是什么逻辑让您循环遍历 DataGridView 的所有行,只是为了更新数据库中的一行。

如果您想更新选中​​或未选中复选框的用户名的 AllowNotification 值,则逻辑如下。

  1. 找出在gridview中被点击的复选框的更新值。
  2. 将更新后的值(True 或 False)存储在布尔变量中。
  3. 从 gridview 同一行的另一个单元格中检索相应的用户名。
  4. 使用条件“WHERE UserName = {userName}”执行更新查询。

DataGridView 的 CellContentClick 事件需要编写如下。

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 1) //Assuming Checkbox is displayed in 2nd column.
    {
        this.dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);

        var result = this.dataGridView1[e.ColumnIndex, e.RowIndex].Value;
        var userName = this.dataGridView1[0, e.RowIndex].Value; //Assumin username is displayed in fist column

        var connectionString = "Your Connection String";
        //Set value of your own connection string above.

        var sqlQuery = "UPDATE UsersNotified SET AllowNotification = @allowNotification WHERE UserName = @userName";

        using (var connection = new SqlConnection(connectionString))
        {
            using (var command = new SqlCommand(sqlQuery, connection))
            {
                command.CommandType = CommandType.Text;
                command.Parameters.Add("@allowNotification", SqlDbType.Bit).Value = result;
                command.Parameters.Add("@UserName", SqlDbType.NVarChar).Value = userName;
                connection.Open();
                command.ExecuteNonQuery();
            }
        }
    }
}

这应该可以帮助您解决问题。

【讨论】:

    【解决方案2】:

    我有一个部分解决方案(它不是 100% 有效,但至少是朝着正确方向迈出的一步):

     private void gvTurnOffNotifications_SelectionChanged(object sender, EventArgs e)
            {
                if (gvTurnOffNotifications.SelectedCells.Count > 0)
                {
                    int selectedrowindex = gvTurnOffNotifications.SelectedCells[0].RowIndex;
    
                    DataGridViewRow selectedRow = gvTurnOffNotifications.Rows[selectedrowindex];
    
                    getUserSelected = Convert.ToString(selectedRow.Cells["UserName"].Value);
    
                    MessageBox.Show(getUserSelected);
    
                    foreach (DataGridViewRow row in gvTurnOffNotifications.Rows)
                    {
                        DataGridViewCheckBoxCell cell = row.Cells[1] as DataGridViewCheckBoxCell;
    
                        //We don't want a null exception!
                        if (cell.Value != null)
                        {
                            //It's checked!
                            btnUpdateTurnOff.Enabled = true;
                            myConnectionString = ConfigurationManager.ConnectionStrings["FSK_ServiceMonitor_Users_Management.Properties.Settings.FSK_ServiceMonitorConnectionString"].ConnectionString;
                            using (mySQLConnection = new SqlConnection(myConnectionString))
                            {
                                bool change = false;
    
                                string procedureName = "update UsersNotified Set AllowNotification='" + change + "' where UserName='" + getUserSelected + "'";
                                //MessageBox.Show(cell.Value.ToString());
                                mySQLCommand = new SqlCommand(procedureName, mySQLConnection);
                                mySQLCommand.CommandType = CommandType.Text;
                                mySQLCommand.Connection = mySQLConnection;
                                mySQLCommand.Connection.Open();
                                mySQLCommand.ExecuteNonQuery();
                            }
                        }
                    }
                }
            }
    

    问题是它只占用了第一行而我没有选择我要取消选择的行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-27
      • 1970-01-01
      • 2011-11-16
      • 1970-01-01
      • 1970-01-01
      • 2014-01-18
      • 1970-01-01
      相关资源
      最近更新 更多