locked
How to update DataGridView Columns when using a binding source. RRS feed

  • Question

  • Hi,

    On my application I use DataGridView tool to display some data from a database in MS SQL Server. The data source are binded from the MS SQL database to Visual Studio project, then i use a datagrid to bind data from one table. When I insert/delete a column on the database table, then I reconfigure the datasource in the VS project to get new changes (updated DataTable) , but the problem is that those changes do not affect datagridview columns, which leads to many runtime errors ( those errors tell that there is in the search query), so I have to edit datagridview properties manually in order to get new edited table columns. Is there any better way to make datagridview columns update automatically depending on project DataTable ( or even better on database columns) ? I am not sure if using Entity Framework gonna help or not.

    Thanks in advance



    Admir

    Tuesday, September 6, 2016 9:58 AM

Answers

  • Hi Admir,

    Thank you for your post.

    >>"Is there any better way to make datagridview columns update automatically depending on project DataTable ( or even better on database columns) ?"

    You could remove all the columns from design view and add columns to DataGridView programatically in code behind. Code below is for your reference. Suppose the name of your datase is 'ds'.

    foreach (DataColumn column in ds.Tables[0].Columns)
    {
        DataGridViewTextBoxColumn dgColumn = new DataGridViewTextBoxColumn();
        dgColumn.Name = column.ColumnName;
        dgColumn.HeaderText = column.ColumnName;
        dgColumn.DataPropertyName = column.ColumnName;
        dataGridView1.Columns.Add(dgColumn);
    }
    Best Regards,
    Li Wang

    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Marked as answer by admiri92 Thursday, September 8, 2016 5:49 AM
    Wednesday, September 7, 2016 1:53 PM