【发布时间】:2021-06-20 23:18:36
【问题描述】:
我使用 C# 创建了一个 Windows 窗体应用程序,用于检查 MySQL 连接是打开还是关闭。对于每个状态,标签的文本都应该改变。
我的问题是:如果应用程序继续运行并且连接关闭或终止,标签的文本不会改变。
我尝试使用 form_load 事件,但没有成功。
这是我的代码:
string connectionString = "Data Source=localhost;Initial Catalog=table;User ID=root;Password=";
public Form1()
{
InitializeComponent();
MySqlConnection cnn = new MySqlConnection(connectionString);
try
{
cnn.Open();
toolStripStatusLabel1.BackColor = System.Drawing.Color.Green;
toolStripStatusLabel1.ForeColor = System.Drawing.Color.White;
toolStripStatusLabel1.Text = "Connection Success";
}
catch (Exception ex)
{
toolStripStatusLabel1.BackColor = System.Drawing.Color.Red;
toolStripStatusLabel1.ForeColor = System.Drawing.Color.White;
toolStripStatusLabel1.Text = "Connection failed!";
}
finally
{
cnn.Close();
}
}
【问题讨论】:
-
订阅 StateChange 事件 dev.mysql.com/doc/dev/connector-net/8.0/html/… 并在您的处理程序中根据 StateChange 参数的值更新您的标签
-
您的代码在表单的
constructor方法中,但构造函数总是只运行一次(在创建表单时)。您可以查看使用Timer组件,例如参见youtube.com/watch?v=98c200lL-OY。我建议不要让它每秒运行一次,否则您的数据库可能会因此而变慢。 -
@PeterB 非常感谢你,我用计时器做到了,它工作得很好