你如何正确覆盖DataGridViewCheckBox.Value?

时间:2009-12-17 13:31:20

标签: .net winforms datagridview

我正在尝试覆盖DataGridViewCheckBox,以便从对象是否在集合(本质上是谓词)中获取它的布尔值,并且当设置该值时,它会根据需要从集合中添加/删除对象。

此外,我希望在显示复选框时检查此值(但是在分配DataGridView之前我无法设置值)。我在CheckBoxCell上尝试了各种方法覆盖的组合(GetValue / SetValue似乎不起作用),我尝试的任何解决方案似乎都不太复杂。

以这种方式覆盖checkboxcell值的最好,最明智和最不忠实的方法是什么?

1 个答案:

答案 0 :(得分:1)

我猜你可以创建一个自定义MyDataGridViewCheckBoxCell并覆盖其GetFormattedValue以返回true \ false,具体取决于集合中存在的单元格值;和SetValue来修改集合。请查看以下示例是否适合您;不确定这是否是最好的方法,但这肯定不是hacky:)

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

希望这有帮助,尊重