1

我正在尝试从我的 SQL 服务器获取信息并根据用户选择的参数将其加载到 datagridview 中。我在这个问题末尾发布的示例在程序的早期函数中工作,但现在不是。这使我相信问题在于实际将数据输出到 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;
            }
4

1 回答 1

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;
于 2012-06-13T20:24:40.120 回答