Click here to Skip to main content
15,911,762 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all can you please help me?

I need to fill a datatable and set it as a datasource for a datagridview my code is below:

C#
private void GenerateGrid(Dictionary<string, string> staticFields) {
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add(COLUMN_NAME);
            dataTable.Columns.Add(COLUMN_VALUE);
            
            int numberOfColumns = staticFields.Keys.Count;
            string[] dynamicColumns = new string[numberOfColumns];
            staticFields.Keys.CopyTo(dynamicColumns, 0);
            foreach (string columnName in dynamicColumns) {
                dataTable.Rows.Add(columnName, "");
            }
            for (int index = 0; index < dynamicColumns.Count(); index++) {
                dataTable.Rows[index][1] = staticFields[dynamicColumns[index]];
            }
            dgvDynamicColumns.DataSource = null;
            dgvDynamicColumns.DataSource = dataTable;
            dgvDynamicColumns.Refresh();


        }


the datagridview is empty although the dictionary is of count 3.

Plz help
Posted
Comments
Stephen Hewison 14-Jun-12 11:42am    
Have you tried stepping through your code to make sure that for each line the state of the data table is being modified as you'd expect it to be? So make sure the rows are being added where they're supposed to. This will help you find the code line which is invalid.

1 solution

Why not simply do the following?
C#
private void GenerateGrid(Dictionary<string,> staticFields)
{
    DataTable dataTable = new DataTable();
    dataTable.Columns.Add("Name");
    dataTable.Columns.Add("Value");
    
    // Step through the KeyValuePairs in the dictionary.
    // Simply add a row for each pair in the dictionary and
    // fill the first column with the keys value
    // and the second with the values value.
    foreach (var pair in staticFields)
    {
        dataTable.Rows.Add(pair.Key, pair.Value);
    }
    
    dgvDynamicColumns.DataSource = null;
    dgvDynamicColumns.DataSource = dataTable;
    dgvDynamicColumns.Refresh();
}
Seems a lot easier to me... By the way, your code sample worked just as well for me.
 
Share this answer
 
Comments
Maciej Los 14-Jun-12 13:35pm    
Good answer, my 5!
Sander Rossel 14-Jun-12 13:58pm    
Thank you :)

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