将数据表加载到数据网格视图中的问题

时间:2012-06-13 19:45:27

标签: c# sql datagridview datatable sqldatasource

我正在尝试从我的SQL服务器获取信息,并根据用户选择的参数将其加载到数据网格视图中。我在这个问题的最后发布的例子在程序的早期函数中工作,但现在不是。这让我相信问题在于实际将数据输出到DGV的那一行。关于为什么它没有填满DGV的任何想法?我已经包含了两个例子,两个都没有用。出于某种原因,他们只是没有向DGV输入任何信息,即使我从调试中知道他们确实成功地从服务器中提取信息。

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;

另一个例子:

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

                dgvOutput.DataSource = Table;
            }

1 个答案:

答案 0 :(得分:0)

你可以试试这个或类似的东西:

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;