首页 > 解决方案 > 如何使用C#检查dataGridView中选定行中的单元格是否为空/空?

问题描述

我正在尝试编写一个代码,该代码检查 dataGridView 中选定行中的单元格是否为空/null,然后单元格将被更新为一个值。我编写的代码有效,但无论所选行中的单元格中是否有值,数据都不会更新。我试过这段代码:

 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 til vagten'',他得到错误:“已经有单元格中的值。”。如果他将选择 ansatID 列下的单元格为空的行,在 textBox1 中写入一个值,然后按 ''Tilføj ansatID til vagten'',然后将执行 SQL 查询并收到消息“单元格已更新”。这也显示在下图中:在此处输入图像描述

标签: c#winformsdatagridviewnullcell

解决方案


在这种情况下,您可以访问所选行中的特定列,您错过了 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()这样的函数并在每次修改数据库时调用它是很方便的。


推荐阅读