简体   繁体   English

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

[英]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. 我试图从我的SQL Server中获取信息,然后根据用户选择的参数将其加载到datagridview中。 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. 这使我相信问题出在将数据实际输出到DGV的生产线上。 Any thoughts on why it's not filling up the DGV? 关于为什么它没有填满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. 由于某种原因,即使我从调试中知道他们确实确实已从服务器成功提取信息,他们也没有将任何信息输入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;

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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