简体   繁体   中英

How to add a column to datagridview usercontrol c# winform

I want to design a new datagridview as usercontrol. It will have a public and browsable property that indicates whether this datagridview has a counter column or not. If it is true then add a new DataGridViewColumn named 'Counter' at 0 index of rows.

This is my usercontrol code:

public partial class UniLibDataGridView : DataGridView
{
    public UniLibDataGridView()
    {
        InitializeComponent();
        if (_HasCounterColumn)
        {
            this.Columns.Add("Counter", "Counter");
        }
    }
    private bool _HasCounterColumn;
    [Browsable(true)]
    [Description("Indicates has Counter Column.")]
    [Category("UniLib Tools")]
    [DisplayName("Has Counter Column")]
    public bool HasCounterColumn
    {
        get { return _HasCounterColumn; }
        set { _HasCounterColumn = value; }
    }

}

It couldn't change the value of _HasCounterColumn at design time.

It cannot work because the designer creates the object (calls the constructor) before it sets the HasCounterColumn property.

Try this instead :

public class UniLibDataGridView : DataGridView
{
    public UniLibDataGridView()
    {
    }

    [Browsable(true)]
    [Description("Indicates has Counter Column.")]
    [Category("UniLib Tools")]
    [DisplayName("Has Counter Column")]
    [DefaultValue(false)]
    public bool HasCounterColumn
    {
        get { return Columns.Contains("Counter"); }
        set
        {
            if (value)
                Columns.Add("Counter", "Counter");
            else if (Columns.Contains("Counter"))
                Columns.Remove("Counter");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM