0

How can i create a property named IsCheck (value true/false) in DataGridViewTextBoxColumn?

i searched the internet but cannot find a solution to create property. Please help me with a code snippet or so.

2 Answers2

2

In addition to TaW's response, I'd suggest you to override Clone() function in order to avoid troubles with the Designer.

class myCheckedColumn : DataGridViewTextBoxColumn
{
    public bool IsChecked { get; set; }

    public myCheckedColumn ()               { IsChecked = false;    }
    public myCheckedColumn (bool checked_)  { IsChecked = checked_; }

    public override object Clone()
    {
        myCheckedColumn clone = (myCheckedColumn)base.Clone();
        myCheckedColumn.IsChecked = IsChecked;
        return clone;
    }
}
Bioukh
  • 1,888
  • 1
  • 16
  • 27
  • After adding the Clone() method, I can set custom properties in the PropertyGrid. But I find that the DataGridViewCell also has Clone() method, and Microsoft copies properties in the DataGridViewCell.Clone(). – cocoa Apr 10 '18 at 03:33
1

Well, you can create it all in the usual way:

class myCheckedColumn : DataGridViewTextBoxColumn
{
    public bool IsChecked { get; set; }

    public myCheckedColumn ()               { IsChecked = false;    }
    public myCheckedColumn (bool checked_)  { IsChecked = checked_; }
}

Now add it to the DataGridView DGV's Columns collection:

    myCheckedColumn checkColumn = new myCheckedColumn (true);
    checkColumn.Name = "checkColumn";
    checkColumn.HeaderText = "some Title";
    checkColumn.MinimumWidth = 120;
    DGV.Columns.Insert(someindex, checkColumn);

And finally we can test it:

private void DGV_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    int col = e.ColumnIndex;
    myCheckedColumn column = DGV.Columns[col] as myCheckedColumn ;
    if (column != null) 
    {
      Console.WriteLine(column.IsChecked.ToString());
      column.IsChecked = !column.IsChecked;
    }
} 

Note: This is a Column, as you have requested, not a Cell! So it has one value per inserted instance of that column.. To create a custom DataGridViewTextBoxCell you would do pretty much the same..

TaW
  • 53,122
  • 8
  • 69
  • 111