I am new to C# and am trying to figure out if there is an easy way to send a DataTable to DataGridView.

6 Years
Discussion Span
Last Post by Mitja Bonca
/// <summary>
    /// Used to set up the data table when the user types a query.
    /// </summary>
    void BuildDataGrid()
        dataGridView1.DataSource = GetSearchResults(queryStr);

    /// <summary>
    /// Connect to the database and then use an adapter to
    /// fill a DataTable.
    /// </summary>
    DataTable GetSearchResults(string queryStr)
        // Make a new DataTable.
        DataTable table = new DataTable();
        // You will want to declare a new DataAdapter, and then call its fill method
        // on the DataTable.
        return table;

Edited by Michael27


After BuildDataGrid is called, the above code sets the DataSource property to the results of another function, GetSearchResults. Next, it performs a custom search. This is custom code that will query a database such as a full-text database for results.


Here is what I have so far

                    MYSQLConnection mysqlConn = new MYSQLConnection();
                    DataTable sqlquery = mysqlConn.Query(queryinput1);
                    BindingSource bs = new BindingSource();
                    bs.DataSource = sqlquery;
                    DataGridView results = new DataGridView();
                    results.DataSource = bs;                                    
                    CSVUtilities util = new CSVUtilities();
                    util.writeTableToCSV(filename1 + ".csv", results, filepath);

I have no problem pulling my sql query and when debugging i can pull my table (sqlquery) and get the results. I'm not getting any errors or anything but somewhere in the middle im missing something.

BTW using VS2005.

Edited by Tobiczyk


You dont need to convert it, but you simply bind it to dgv. Using dataSource property of dgv, assgin dataTable to it:

dgv.DataSource = dataTable.DefaultView;
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.