![](/img/trans.png)
[英]How to Check Selected Row In Datagridview without Checking the Cell in C#
[英]How to check if a cell in selected row in dataGridView is empty/null, using C#?
我正在尝试编写一个代码,该代码在使用值更新单元格之前检查 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 til vagten'',他得到错误:“已经有单元格中的一个值。”。 如果他将选择 ansatID 列下的单元格为空的行,在 textBox1 中写入一个值,然后按“Tilføj ansatID til 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中手动更新数据网格中的数据,有一个像UpdateDatagrid()这样的函数并在每次修改数据库时调用它是很方便的。
您可以使用String.IsNullOrWhiteSpace((String)dataGridView1.SelectedCells[0].OwningRow.Cells[1].Value))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.