gpt4 book ai didi

c# - 无法在 OnRowChanging 事件中调用 CancelEdit()

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

private void Cource_Load(object sender, EventArgs e)
{
//fill dataset by using .GetAllCourses() function
DataSet ds = new DataAccess.newCourcesDAC().GetAllCourses();

//define and set BindingSource to tblCourses of dataset
BindingSource BS = new BindingSource();
BS.DataSource = ds;
BS.DataMember = "tblCourses";

//bind datagridview to Bindingsource
ds.Tables["tblCourses"].RowChanging += new DataRowChangeEventHandler(Cource_RowChanging);
dataGridView1.DataSource = BS;

//bind for texbox to navigat 4 column of Cource table
txtCourseID.DataBindings.Add("Text", BS, "CourseID");
txtCourseName.DataBindings.Add("Text", BS, "CourseName");
txtPrequest.DataBindings.Add("Text", BS, "Prequest");
txtCourseContent.DataBindings.Add("Text", BS, "CourseContent");
}
**void Cource_RowChanging(object sender, DataRowChangeEventArgs e)
{
if ( e.Action==DataRowAction.Add)
{
if (((int)e.Row["CourseID", DataRowVersion.Proposed]) < 10)
{
e.Row.SetColumnError("CourseID", "cource id must < 10");
e.Row.CancelEdit();
}
}
}**

我有一个数据集 (ds) 和一个表 (tblCourse),它有 4 列,使用绑定(bind)源绑定(bind)到 4 个文本框。我想在通过 RowChanging 事件向数据表添加新记录时验证数据。

我想在指定条件发生时使用 [ e.Row.CancelEdit();] 取消行。

但我收到这个错误:无法在 OnRowChanging 事件中调用 CancelEdit()。抛出异常以取消此更新。

最佳答案

为了任何可能偶然发现这个旧线程的人的利益,我将发布一个解决方案来解决与这个问题相关的一些“陷阱”。

  1. 无论错误消息怎么说,在 RowChanging 中抛出异常并结合 Try-Catch 都不会删除新行。我不能说它从不在抛出错误时删除该行,只是我还没有看到它发生过。

  2. 在没有 Try-Catch 的情况下抛出异常会将行标记为有错误。如果您有任何 WPF 数据网格代码来指示验证错误——例如显示我喜欢的红色复选标记——那么错误将被正确显示。不过该行不会被删除。

  3. 在我迄今为止见过的任何情况下,在 RowChanging 中调用 e.Delete 也不会删除该行。如果设置断点并检查 RowState,它将被设置为 Detached。当接下来触发 RowChanged 事件时,RowState 将恢复为 e.Added。即使可以在某些其他条件下删除 RowChanging 中的行,也可能不会将数据集或后端数据库中的任何标识列重置回添加之前的最后一个值。

  4. 下面我相当简单的 VB.Net 变通方法使用标志变量(我通常将其放在数据类级别)来识别 RowChanging 中是否发生了取消,然后在 RowChanged 中采取适当的操作并重置标志.到目前为止,我还没有遇到任何问题,除了一些“此行已从表中删除并且没有任何数据。BeginEdit() 将允许在此行中创建新数据。”当遇到已删除的行时,我的代码中其他地方出现异常,这些异常通过对 RowState 设置为 Detached 的一些简单检查来修复。我希望这会有所帮助。

    私有(private) LastRowAdditionCanceled 作为 bool 值

    Public Sub RowChanging(ByVal sender As Object, ByVal e As DataRowChangeEventArgs)

    If e.Action = DataRowAction.Add Then
    'Add the conditions where you want to cancel the row addition above
    LastRowAdditionCanceled = True
    End If
    End Sub



    Public Sub RowChanged(ByVal sender As Object, ByVal e As DataRowChangeEventArgs)

    If LastRowAdditionCanceled = False Then
    'execute your usual RowChanged code here

    Else
    e.Row.RejectChanges()
    LastRowAdditionCanceled = False
    End If
    End Sub

关于c# - 无法在 OnRowChanging 事件中调用 CancelEdit(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11536529/

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