问题
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