C# 如何使用C检查dataGridView中选定行中的单元格是否为空/空?

C# 如何使用C检查dataGridView中选定行中的单元格是否为空/空?,c#,winforms,datagridview,null,cell,C#,Winforms,Datagridview,Null,Cell,我正在尝试编写一段代码,在使用值更新单元格之前,检查dataGridView中选定行中的单元格是否为空/空。我编写的代码可以工作,但无论选定行的单元格中是否有值,数据都不会更新。我已尝试使用此代码: if (dataGridView1.SelectedRows[0].Cells[1].Value == null) { try { String ConnectionSt

我正在尝试编写一段代码,在使用值更新单元格之前,检查dataGridView中选定行中的单元格是否为空/空。我编写的代码可以工作,但无论选定行的单元格中是否有值,数据都不会更新。我已尝试使用此代码:

 if (dataGridView1.SelectedRows[0].Cells[1].Value == null)
            {
                try
                {
                    String ConnectionString = @"Data Source=.\SQLEXPRESS01;Initial Catalog=Vagtplan;Integrated Security=True";
                    SqlConnection myconnection = new SqlConnection(ConnectionString);
                    myconnection.Open();
                    DateTime primaryKey = Convert.ToDateTime(dataGridView1.SelectedRows[0].Cells[0].Value);
                    SqlCommand AddNumbeCommand = myconnection.CreateCommand();
                    AddNumbeCommand.CommandText = "UPDATE dbo.Vagter SET [ansatID] = @ansatID WHERE [Dato] = @dato";
                    AddNumbeCommand.Parameters.Add("@ansatID", SqlDbType.Int).Value = textBox1.Text;
                    AddNumbeCommand.Parameters.Add("@dato", SqlDbType.DateTime).Value = primaryKey;
                    AddNumbeCommand.ExecuteNonQuery();
                    myconnection.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    MessageBox.Show("The cell is updated.");
                }

            }
            else
            {
                MessageBox.Show("There is already a value in the cell.");
            }

正如我之前提到的,实际结果是,无论选定行中的单元格中是否有值,数据都不会更新。预期结果是,当用户在dataGrdView中选择一行,其中列ansatID下的单元格已经有值,在textBox1中写入一个值,然后按Tilføj ansatID直到vagten时,他会得到错误:单元格中已经有值。。如果他选择一行,其中列ansatID下的单元格为空,在textBox1中写入一个值,然后按Tilføj ansatID直到vagten,那么SQL查询将被执行,他将收到消息“单元格已更新”。下图也显示了这一点:

在这种情况下,您可以访问所选行中的特定列,您错过了OwningRow部分,您需要与空字符串和null进行比较,以防万一:

(string)dataGridView1.SelectedCells[0].OwningRow.Cells[1].Value == "" ||
(string)dataGridView1.SelectedCells[0].OwningRow.Cells[1].Value == null
SelectedCells[0]。OwningRow表示第一个选定的行,Cells[1]表示是ansatID

我喜欢winforms和它的清晰


编辑:正如有人指出的,您需要在winforms中手动更新datagrid中的数据,使用类似UpdateDatagrid的函数并在每次修改DB时调用它是很方便的。

您可以使用String.IsNullOrWhiteSpaceStringdataGridView1.SelectedCells[0].OwningRow.Cells[1].Value

此代码更新数据库而不是datagridview。更新数据库不会自动更改网格中显示的数据。OP使用的是SelectedRows而不是SelectedCells。无论如何,这种方法代替SelectedRows有什么好处?@Jose Antonio Navarro Marco当我尝试更新时,出现以下错误:“System.InvalidCastException:类型为'System.DBNull'的对象无法转换为'System.String'类型。”