Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

c# - Why DataGridColumn not getting removed from DataGridView

I have custom DataGridView control and in that control there is RefreshGrid() method which fill DataGridView by using DataSource. Now I am tring to remove few columns from that DataGridView after DataSource binding but unable to remove those, those column not getting removed but add at the end of DataGridView, when I call RefreshGrid() method again then those column get removed from DataGridView. Here is code for method RefreshGrid()

    public void RefreshGrid()
    {
        DataTable _table = AccessConnectionManagers.GetDataTableBySQLQuery("select Colm1,Colm2,Colm3 from TableName");
        //Data Source Binding with DataGridView
        this.DataSource = _table;

        if (!string.IsNullOrEmpty("Colm1"))
        {
            var _colmArray = GridRemoveColumnName.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries).Where(a => this.Columns.Contains(a)).Select(a => a).ToArray();

            foreach (string colm in _colmArray)
            {
                //Remove column after Source Binding
                this.Columns.Remove(colm);
            }
        }
    }

Call for RefreshGrid()

    public Form1()
    {
        InitializeComponent();
        myDataGridView1.RefreshGrid();
    }

Please find the error and suggest me the solution.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found answer for this question

I need to call RefreshGrid() method on Form Load not on Form constructor, after calling it on Form Log my problem get solved. But I dont know why it wasnt working on Form constructor.

I guess you try to access columns that do not exist yet. You are using the DataGridView.AutoGenerateColumns functionnality and even if you set the DataSource property, The DatagridView won't create columns until the grid is displayed. It's why it doesn't work in form constructor, but works in form_Load event or after that the grid has been displayed.

Using form_Load is maybe a possible workaround, but I reommand you to use the DataGridView.DataBindingComplete event which is especially designed to handle this situation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...