将DataGridView Checked Record更新到数据库

时间:2017-06-28 11:09:01

标签: c# sql sql-server

所以我有这个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();
                     }
                 }
             }
         }
     }

然后当我点击我的"更新"按钮,我想发送更新的griddata以存储在我的数据库中,如下所示:

 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);
            }
        }

我的Update块中的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=0

关于如何实现这一目标的任何建议?

2 个答案:

答案 0 :(得分:1)

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

如果您要为选中或取消选中复选框的用户名更新AllowNotification值,则逻辑将为此。

  1. 计算出在gridview中单击的复选框的更新值。
  2. 将更新后的值(True或False)存储在布尔变量中。
  3. 从gridview的同一行的其他单元格中检索相应的用户名。
  4. 使用条件执行更新查询" WHERE UserName = {userName}"。
  5. 您需要编写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();
                }
            }
        }
    }
    

    这可以帮助您解决问题。

答案 1 :(得分:0)

我有一个部分解决方案(它不是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();
                        }
                    }
                }
            }
        }

问题是它只是在第一行没有我选择了我想取消选择的行。