Datagridview mask values in column

非 Y 不嫁゛ 提交于 2019-12-11 11:49:40

问题


How can I "mask" the values of a datagridview in a windows forms application? In example, how can I limit the value in a column datagridviewtextboxcolumn so that is not bigger than a given number? (i.e. cell value in that column < 9.6) I build my datagridview programmatically at runtime.


回答1:


You can just use if() on CellEndEdit event handler




回答2:


The easiest way to do this, if possible, is to validate the value at the entity level.

For instance, say we have the following simplified Foo entity;

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;
            }
        }
    }
}

Now we can bind to our DataGridView a List<Foo> foos and we will be effectively masking any input in the "Type" DataGridViewColumn.

If this isn't a valid path, then simply handle the CellEndEdit event and validate the input.



来源:https://stackoverflow.com/questions/6411511/datagridview-mask-values-in-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!