簡體   English   中英

將數據表加載到數據網格視圖中的問題

[英]loading a data table into a data grid view problems

我試圖從我的SQL Server中獲取信息,然后根據用戶選擇的參數將其加載到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;
            }

您可以嘗試以下方法或類似方法:

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