You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#调用自定义询问弹窗选No时如何终止执行后续代码

解决方案

当前问题核心是:MessageTextQues 方法是无返回值的void类型,调用方无法感知用户在弹窗中的选择结果,所以无论用户选Yes还是No,方法执行完成后都会自动运行后续的刷新代码,以下是两种可行实现方案:

方案1:修改静态方法返回布尔值判断选择结果(推荐)

第一步:修改Helper类代码

将MessageTextQues的返回值改为bool类型,用户选Yes时返回true,选No/直接关闭弹窗时返回false:

class Helper
{
    public static bool MessageTextQues(string text, Action action)
    {
        MessageQues messageQues = new MessageQues();
        messageQues.lblText.Text = text;
        messageQues.ShowDialog();

        if (messageQues.DialogResult == DialogResult.Yes)
        {
            action();
            return true;
        }
        // 选No或者其他操作统一返回false
        return false;
    }
}

第二步:修改调用处代码

调用时接收方法返回值,只有返回值为true(即用户确认删除)时才执行刷新逻辑:

bool isDeleteConfirmed = Helper.MessageTextQues(
    $@"This material '{dgMaterials.CurrentRow.Cells[2].Value}' will delete. Do you want? ",
    () => material.MaterialDelete(Convert.ToInt32(dgMaterials.CurrentRow.Cells[1].Value)));

// 仅用户确认删除后才执行刷新操作
if (isDeleteConfirmed)
{
    btnRefresh_Click(sender, e);
}

方案2:将后续逻辑封装到委托中传入(无需修改Helper类)

如果不想调整Helper类的原有定义,可以把刷新逻辑也合并到传入的Action委托中,这样只有用户选Yes时才会一起执行删除和刷新逻辑:

Helper.MessageTextQues(
    $@"This material '{dgMaterials.CurrentRow.Cells[2].Value}' will delete. Do you want? ",
    () => 
    {
        material.MaterialDelete(Convert.ToInt32(dgMaterials.CurrentRow.Cells[1].Value));
        btnRefresh_Click(sender, e);
    });

内容的提问来源于stack exchange,提问作者Shams Tech

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 18:54:05