Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I am trying to populate a data grid pragmatically from a data set table using the code below ;-

C#
private void WOTest_Load(object sender, EventArgs e)
        {
            FormDataSet = woutil.GetDataset;
            dgComments.DataSource = FormDataSet.Tables["PREWODOC_COMMENTS"];
            foreach (DataColumn col in FormDataSet.Tables["PREWODOC_COMMENTS"].Columns)
            {
                dgComments.Columns.Add(col.ColumnName, col.ColumnName);
            }
        }

This code does create the columns in the data grid however instead of having the 4 columns I was expecting I get 8 columns because the columns are duplicated. How can I stop the columns duplicating I have stepped the code and the call to add the columns is only done 4 times as I would expect so I do not understand why there are 8 columns as there are only 4 added?
Posted
Updated 30-Oct-14 23:34pm
v2
Comments
Member 11123297 30-Oct-14 11:36am    
No that isn't the problem the grid is new only placed on the form with no data bindings or columns added. To check I have just adde a new grid and tried the code against that and the columns are still duplicated.

You have the columns already bound in the design area and so in code you are adding them again. Just comment out the foreach loop that adds them.
 
Share this answer
 
I was unaware that the auto generate columns attribute was set to true by default setting this to false before adding the columns has solved the issue.

C#
private void WOTest_Load(object sender, EventArgs e)
{
    FormDataSet = woutil.GetDataset;
    dgComm.DataSource = FormDataSet.Tables["PREWODOC_COMMENTS"];
    dgComm.AutoGenerateColumns = false;
    foreach (DataColumn col in FormDataSet.Tables["PREWODOC_COMMENTS"].Columns)
    {
        dgComm.Columns.Add(col.ColumnName, col.ColumnName);
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900