如何在C#中使用MessageBox打印SQL查询

时间:2015-03-22 10:38:38

标签: sql c#-4.0

我从昨天开始就遇到了这个问题。我创建了一个按钮,单击该按钮可显示SQL Server表的结果。我想过使用MessageBox来打印这些结果,或者是否有其他方法可以打印结果?

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        SqlConnection con = new SqlConnection("Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True");
        SqlCommand command = new SqlCommand("SELECT * FROM Products", con);

        con.Open();

        SqlDataReader reader = command.ExecuteReader();
        command.ExecuteNonQuery();

        con.Close();
    }
    catch (Exception es)
    {
        MessageBox.Show(es.Message);
    }
}

我尝试了不同的方法,但从未奏效过......我真的被卡住了。如果您想了解更多详情,请与我们联系。感谢您的帮助

2 个答案:

答案 0 :(得分:0)

您需要使用SqlDataReader迭代返回的行,从每行中提取所需内容,然后将其显示给最终用户。

我修改了你的代码,使它更安全(using阻止!),我修改了查询只返回产品名称(假设你有),因为你无法真正显示消息框中的整行 ....

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        string connectionString = "Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True";
        string query = "SELECT ProductName FROM Products;";

        using (SqlConnection con = new SqlConnection(connectionString))
        using (SqlCommand command = new SqlCommand(query, con))
        {
            con.Open();

            using (SqlDataReader reader = command.ExecuteReader())
            {
               while (reader.Read()) 
               {
                    string productName = reader.GetFieldValue<string>(0);
                    MessageBox("Product is: " + productName);
               }

               reader.Close();
            }

            con.Close();
        }
    }
    catch (Exception es)
    {
        MessageBox.Show(es.Message);
    }
}

答案 1 :(得分:0)

添加datagridview控件以显示多行并尝试此代码并将其重命名为您想要的内容并从您为datagridview控件设置的名称中替换此YourDataGridVeiwName并尝试下面的代码

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        string connectionString = "Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True";
        string query = "SELECT ProductName FROM Products;";

        using (SqlConnection con = new SqlConnection(connectionString))
        using (SqlCommand command = new SqlCommand(query, con))
        {
            con.Open();

            using (SqlDataAdapter sda = new SqlDataAdapter(command))
            {

              DataTable dt = new DataTable(); 
              sda.Fill(dt);
              YourDataGridVeiwName.DataSource= dt;
             }

            con.Close();
        }
    }
    catch (Exception es)
    {
        MessageBox.Show(es.Message);
    }
}