gpt4 book ai didi

c# - 允许用户取消在 datagridview 中的编辑

转载 作者:太空宇宙 更新时间:2023-11-03 10:43:55 25 4
gpt4 key购买 nike

我有一个处理了 CellValidating 和 RowValidating 事件的 datagridview。我的问题是,当我单击它然后改变主意并想取消对当前行的编辑时,这些验证方法不会让我这样做,如果它是第一行,它似乎在已经有一些有效的情况下起作用行,但当它是第一行时,它不会让我将焦点更改为其他内容。

所以我的问题是我怎样才能同时拥有验证和取消对 datagridview 行的编辑的能力?我不介意取消编辑时 datagridview 中的当前行是否丢失。

编辑:这是我的验证方法:

private void Neighbours_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex == 2)
{
int i = 0;
if (!int.TryParse(e.FormattedValue.ToString(), out i) || i <= 0)
{
e.Cancel = true;
Neighbours.Rows[e.RowIndex].ErrorText = "error";
}
}
}

private void Neighbours_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
{
DataGridViewRow r = ((DataGridView)sender).Rows[e.RowIndex];
int dist = 0;
if (r.Cells["NeighboursStop1"].Value == null || r.Cells["NeighboursStop1"].Value.ToString() == "" || r.Cells["NeighboursStop2"].Value == null || r.Cells["NeighboursStop2"].Value.ToString() == "")
{
e.Cancel = true;
r.ErrorText = "error";
}
else if (r.Cells["NeighboursStop1"].Value.ToString() == r.Cells["NeighboursStop2"].Value.ToString())
{
e.Cancel = true;
r.ErrorText = "error";
}
else if(!int.TryParse(r.Cells["NeighboursDistance"].Value.ToString(), out dist))
{
e.Cancel = true;
r.ErrorText = "error";
}
else if (dist <= 0)
{
e.Cancel = true;
r.ErrorText = "error";
}
else
{
r.ErrorText = "";
}
}

这是它发生时的样子,如果我按下 Escape 键,错误消息就会消失,但是当我尝试单击其他内容时,RowValidation 再次发生并且我回到这个状态:

error

EDIT2:我使用数据表作为这个数据 GridView 的数据源。

最佳答案

我无法测试代码,但您可以尝试以下方法吗?

   private void Neighbours_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
{

//Include this, check to see if the row is dirty
if (Neighbours.Rows[e.RowIndex] != null && !Neighbours.Rows[e.RowIndex].IsNewRow && Neighbours.IsCurrentRowDirty)
{



DataGridViewRow r = ((DataGridView)sender).Rows[e.RowIndex];
int dist = 0;
if (r.Cells["NeighboursStop1"].Value == null || r.Cells["NeighboursStop1"].Value.ToString() == "" || r.Cells["NeighboursStop2"].Value == null || r.Cells["NeighboursStop2"].Value.ToString() == "")
{
e.Cancel = true;
r.ErrorText = "error";
}
else if (r.Cells["NeighboursStop1"].Value.ToString() == r.Cells["NeighboursStop2"].Value.ToString())
{
e.Cancel = true;
r.ErrorText = "error";
}
else if(!int.TryParse(r.Cells["NeighboursDistance"].Value.ToString(), out dist))
{
e.Cancel = true;
r.ErrorText = "error";
}
else if (dist <= 0)
{
e.Cancel = true;
r.ErrorText = "error";
}
else
{
r.ErrorText = "";
}
}

}

关于c# - 允许用户取消在 datagridview 中的编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24222882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com