在Datagridview中显示数据库搜索结果

时间:2015-05-29 19:45:13

标签: c# sql-server winforms visual-studio-2013 datagridview

我在Windows窗体应用程序c#中使用Visual Studio 2013和SQL Server 2012 for database。

我想在.GetMany(u => u.UserName == "username");

中显示我的查询搜索结果
DataGridView

我在public void customerSearch(int custID, DataGridView dataGridView) { try { SqlConnection connection = new SqlConnection(@"Connection String"); connection.Open(); SqlCommand searchQuery = new SqlCommand("select * from [Customer] where custId = @custID", connection); searchQuery.Parameters.AddWithValue("@custId", custID); //searchQuery.ExecuteNonQuery(); using (SqlDataReader reader = searchQuery.ExecuteReader()) { while (reader.Read()) { dataGridView.DataBindings.ToString(); } } } catch (SqlException Exception) { MessageBox.Show(Exception.ToString()); } finally { connection.Close(); } } } 获得NullReferenceException 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:4)

当您将连接置于USING中时,它会在块退出时自动关闭并处理您的连接。

public void customerSearch(int custID, DataGridView dataGridView)
        {
            using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString))
            {
                try
                {

                    connection.Open();

                    SqlCommand searchQuery = new SqlCommand("select * from [Customer] where custId = @custID", connection);
                    searchQuery.Parameters.Add("@custId", SqlDbType.Int).Value = custID;
                    //searchQuery.ExecuteNonQuery();

                    using (SqlDataReader reader = searchQuery.ExecuteReader())
                    {
                        DataTable dt = new DataTable();
                        dt.Load(reader);
                        dataGridView.AutoGenerateColumns = true;
                        dataGridView.DataSource = dt;
                        dataGridView.Refresh();
                    }
                }
                catch (SqlException Exception)
                {
                    MessageBox.Show(Exception.ToString());
                }
            }
        }

- 编辑 -

您无法将DataGridView绑定到DataReader。我编辑了上面的代码来演示一种方法。我只是从您的阅读器创建一个DataTable并将网格绑定到DataTable。