2009-12-17 77 views
0

我想覆盖DataGridViewCheckBox,以便它是从一个对象是否在一个集合(本质上是一个谓词)中取得它的布尔值,并且当设置该值时,它会根据需要向集合中添加/删除对象。如何正确覆盖DataGridViewCheckBox.Value?

此外,我希望在显示复选框时检查此值(但在指定DataGridView之后,我无法设置值)。我已经尝试了CheckBoxCell(GetValue/SetValue似乎无法工作)的方法覆盖的各种组合,并且我尝试的任何解决方案似乎都不是很复杂。

什么是最好的,最明智的和最简单的方法来覆盖复选框单元格值这种方式?

回答

1

我想你可以创建一个自定义的MyDataGridViewCheckBoxCell并覆盖它的GetFormattedValue来返回true \ false,取决于存在单元的值在你的集合中;和SetValue来修改集合。请看下面的例子是否适合你的工作。不知道这是否是做到这一点的最好办法,但它不是哈克这是肯定的:)

private static List<string> ItemsList = new List<string>(); 
... 
// fill in collection list 
ItemsList.AddRange(new string[] { "a", "c" }); 
// create columns 
DataGridViewTextBoxColumn column0 = new DataGridViewTextBoxColumn() 
    { HeaderText = "column1", DataPropertyName = "Column1"}; 
DataGridViewCheckBoxColumn column1 = new NewDataGridViewCheckBoxColumn() 
    { HeaderText = "column2", DataPropertyName = "Column2"}; 
dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { column0, column1 }); 
// create data rows 
dataSet1.Tables[0].Rows.Add(new object[] {"a", "a" }); 
dataSet1.Tables[0].Rows.Add(new object[] { "b", "b" }); 
dataSet1.Tables[0].Rows.Add(new object[] { "c", "c" }); 
... 
// custom datagridview checkbox cell 
public class MyDataGridViewCheckBoxCell : DataGridViewCheckBoxCell 
{ 
    public MyDataGridViewCheckBoxCell() 
    { 
     FalseValue = false; 
     TrueValue = true; 
    } 

    protected override Object GetFormattedValue(Object value, 
     int rowIndex, 
     ref DataGridViewCellStyle cellStyle, 
     TypeConverter valueTypeConverter, 
     TypeConverter formattedValueTypeConverter, 
     DataGridViewDataErrorContexts context) 
    { 
     // check if value is string and it's in the list; return true if it is 
     object result = (value is string) ? Form1.ItemsList.IndexOf((string)value) > -1 : value; 
     return base.GetFormattedValue(result, rowIndex, ref cellStyle, 
      valueTypeConverter, formattedValueTypeConverter, context); 
    } 

    protected override bool SetValue(int rowIndex, Object value) 
    { 
     if (value!=null) 
     { 
      // change collection 
      if (value.Equals(true)) 
       Form1.ItemsList.Add((string)Value); 
      else 
       Form1.ItemsList.Remove((string)Value); 

      // dump list into console 
      foreach (string item in Form1.ItemsList) 
       Console.Write("{0}\t", item); 
      Console.WriteLine(); 
     } 
     return true; 
    } 
}   
// custom datagridview column  
public class NewDataGridViewCheckBoxColumn : DataGridViewCheckBoxColumn 
{ 
    public NewDataGridViewCheckBoxColumn() 
    { 
     CellTemplate = new MyDataGridViewCheckBoxCell(); 
    } 
} 

希望这会有所帮助,至于