2011-06-20 61 views
1

如何在Windows窗體應用程序中「掩碼」datagridview的值?例如,如何限制列datagridviewtextboxcolumn中的值,使其不大於給定數字? (即該列中的單元格值爲< 9.6) 我在運行時以編程方式構建我的datagridview。列中的Datagridview掩碼值

回答

3

您只需在CellEndEdit事件處理

+0

完美。用這種方式,用戶對他的行爲有直接的反饋。如果我在最大值爲8時插入9,我可以捕捉到它並將其更改爲一次。也許不是那麼好的表演,但很好的圖形效果。 – Francesco

2

使用if()做最簡單的方法,如果可能的話,是在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; 
      } 
     } 
    } 
} 

我們可以綁定到我們的DataGridView一個List<Foo> foos,我們將有效地屏蔽在"Type" DataGridViewColumn任何輸入。

如果這不是一個有效的路徑,那麼只需處理CellEndEdit事件並驗證輸入。

+0

很好的答案。但通過這種方式,我能否主動約束直接反饋給用戶的價值觀? – Francesco

+0

@Francesco:給出錯誤消息可能更麻煩。但用戶確實以某種方式得到了直接的反饋,因爲他會在他嘗試提交時立即取消其編輯。例如,在我給你的例子中,如果最終用戶在'Type'字段'DataGridViewCell'中輸入'8',當他提交該值(命中輸入)時,它將作爲修改返回到原始值不能在底層的「實體」中設置。 – InBetween