【问题标题】:Datagridview mask values in column列中的 Datagridview 掩码值
【发布时间】:2011-09-18 16:25:14
【问题描述】:

如何在 Windows 窗体应用程序中“屏蔽”datagridview 的值?例如,如何限制 datagridviewtextboxcolumn 列中的值,使其不大于给定数字? (即该列中的单元格值

【问题讨论】:

    标签: c# datagridview masking


    【解决方案1】:

    如果可能,最简单的方法是验证 entity 级别的值。

    例如,假设我们有以下简化的Foo 实体;

    public class Foo
    {
        private readonly int id;
        private int type;
        private string name;
    
        public Foo(int id, int type, string name)
        {
            this.id = id;
            this.type = type;
            this.name = name;
        }
    
        public int Id { get { return this.id; } }
    
        public int Type
        {
            get
            {
                return this.type;
            }
            set
            {
                if (this.type != value)
                {
                    if (value >= 0 && value <= 5) //Validation rule
                    {
                        this.type = value;
                    } 
                }
            }
        }
    
        public string Name
        {
            get
            {
                return this.name;
            }
            set
            {
                if (this.name != value)
                {
                    this.name = value;
                }
            }
        }
    }
    

    现在我们可以绑定到我们的DataGridViewList&lt;Foo&gt; foos,我们将有效地屏蔽"Type" DataGridViewColumn 中的任何输入。

    如果这不是有效路径,则只需处理 CellEndEdit 事件并验证输入。

    【讨论】:

    • 好答案。但是通过这种方式,我是否可以主动约束向用户提供直接反馈的值?
    • @Francesco:提供错误消息可能更麻烦。但是用户确实会以某种方式获得直接反馈,因为他会看到他的编辑在他尝试提交时立即被取消。例如,在我给您的示例中,如果最终用户在Type 字段DataGridViewCell 中输入8,当他提交值(按回车键)时,它将立即切换回原始值作为修改无法在底层entity中设置。
    【解决方案2】:

    您可以只在 CellEndEdit 事件处理程序上使用 if()

    【讨论】:

    • 完美。以这种方式,用户对他的动作有直接的反馈。如果我在最大值为 8 时插入 9,我可以捕获并更改一次。可能性能不是很好,但图形效果很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-27
    • 1970-01-01
    • 2015-12-03
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    相关资源
    最近更新 更多