连接到SQL Server后显示成功的消息

时间:2016-05-18 12:51:07

标签: c# sql-server winforms

我在C#中使用以下代码连接到我的SQL Server,它运行正常。但我想向用户显示一条消息,说如果连接成功与否,并且不知道如何做到这一点。有谁可以帮助我?

这是我的代码:

string cs = "Data Source=IS020114\\CODRINMA;Initial Catalog=gcOnesti;Integrated Security=True";

private void conectareToolStripMenuItem_Click(object sender, EventArgs e)
 {
        try
        {
            using (SqlConnection con = new SqlConnection(cs))
            {
                con.Open();

            }
        }
        catch (Exception er) {
            MessageBox.Show(er.Message);
                }

    }

2 个答案:

答案 0 :(得分:1)

您自己提供了答案。请尝试以下代码:

string cs = "Data Source=IS020114\\CODRINMA;Initial Catalog=gcOnesti;Integrated Security=True";

private void conectareToolStripMenuItem_Click(object sender, EventArgs e)
{
        try
        {
            using (SqlConnection con = new SqlConnection(cs))
            {
                con.Open();
                MessageBox.Show("Connection successful !!");    
            }
        }
        catch (Exception er) {
            MessageBox.Show("Connection unsuccessful..");
        }

}

答案 1 :(得分:0)

我不确定你想要什么,我不确定你是否有任何想要发布消息的控件,但是一个简单的消息框就是这样的:

string cs = "Data Source=IS020114\\CODRINMA;Initial Catalog=gcOnesti;Integrated Security=True";

private void conectareToolStripMenuItem_Click(object sender, EventArgs e)
 {
    try
    {
        using (SqlConnection con = new SqlConnection(cs))
        {
            con.Open();
            MessageBox.Show("Yay! You're connected!");

        }
    }
    catch (Exception er) 
    {
        MessageBox.Show(er.Message);
    }
}