Programmatically create the DataGrid columns not working RRS feed

  • Question

  • I dragged a DataGrid (dataGrid1) from the toolbox to the form and did not bind to any datasource. Then codes below programmatically creates the grid columns but it is not working. What did I miss?

    string path;
    path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
    string connectionString = "Data Source=" + path + "\\database.sdf";
    string sqlStatement = "SELECT * FROM Table1 WHERE Table1.Country = 'United Kingdom'";
    SqlCeConnection connection = new SqlCeConnection(connectionString);
    SqlCeDataAdapter adapter = new SqlCeDataAdapter(sqlStatement, connection);
    DataSet DS = new DataSet();
    adapter.Fill(DS, "Table1");
    DataGridTableStyle tableStyle = new DataGridTableStyle();
    DataGridTextBoxColumn COUNTRY = new DataGridTextBoxColumn();
    DataGridTextBoxColumn CITY = new DataGridTextBoxColumn();
    tableStyle.MappingName = DS.Tables[0].GetType().Name;
    COUNTRY.MappingName = "COUNTRY";
    COUNTRY.HeaderText = "Country";
    COUNTRY.Width = 100;
    CITY.MappingName = "CITY";
    CITY.HeaderText = "City";
    CITY.Width = 100;
    dataGrid1.DataSource = DS.Tables[0];

    I did this above and it still show all other Columns defined in the Table.
    Wednesday, May 23, 2012 7:00 AM

All replies




    First, I would suggest you to diagnosis if it is caused by the SQL connect.


    You can use try-catch block on the connection function, to catch the connect error.


    Best regards,


    Jesse Jiang [MSFT]
    MSDN Community Support | Feedback to us

    Thursday, May 24, 2012 5:30 AM