简体   繁体   中英

loading a data table into a data grid view problems

I'm trying to take information from my SQL server and load it into a datagridview based on paramaters selected by the user. The example I post at the end of this question worked in an earlier function in the program, but now it isn't. This leads me to believe that the issue lies in the line that actually outputs the data to the DGV. Any thoughts on why it's not filling up the DGV? I've included two examples, neither of which is working. For some reason, they're just not inputting any information into the DGV, even though I know from debugging that they are indeed pulling the information from the server successfully.

SqlConnection DBConnection = new SqlConnection(ConnectionString);

        //Opens the connection
        DBConnection.Open();

        //Creates a string to hold the query
        string query = "SELECT * FROM PRD WHERE PRD_NUM LIKE '" +OutputBeforeIncrement + "%'";

        //Creates an SQLCommand object to hold the data returned by the query 
        SqlCommand queryCommand = new SqlCommand(query, DBConnection);        

        //Uses the aforementioned SQLCommand to create an SQLDataReader object
        SqlDataReader queryCommandReader = queryCommand.ExecuteReader();      

         //Creates a DataTable to hold the data                               
        DataTable dataTable = new DataTable();

        //This part actually loads the data from the query into the table     
        dataTable.Load(queryCommandReader);
        dgvOutput.DataSource = dataTable;

The other example:

using (SqlDataAdapter newDA = new SqlDataAdapter(query, DBConnection))
            {
                DataTable Table = new DataTable();
                newDA.Fill(Table);

                dgvOutput.DataSource = Table;
            }

You might try this or something similar:

SqlDataAdapter myDataAdapter;
SqlCommandBuilder myCommandBuilder;
SqlCommand mySqlCommand = new SqlCommand(myQuery, MySQLConnection);
//I think this is the default command type, and thus can be omitted
mySqlCommand.CommandType = CommandType.Text; 
myDataAdapter = new SqlDataAdapter(mySqlCommand);
//Automates your insert/update/delete
myCommandBuilder = new SqlCommandBuilder(myDataAdapter);
myDataAdapter.Fill(myDataTable);
dgvOutput.DataSource = myDataTable.DefaultView;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM