具有多个事件的 C# 按钮

标签 c# mysql database label

我试图通过始终单击同一个按钮来多次覆盖标签中的内容。不幸的是,我只知道如何覆盖它一次。 我面临的问题是标签中的数据来自 SQL 数据库,它只显示标签中 ID = 1 的数据。

这是我的代码:

MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); // Connectionstring to the database
    public MainWindow()
    {
        InitializeComponent();
    }
    private void btContinue_Click(object sender, RoutedEventArgs e)
    {
            try
            {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand("SELECT l_question from l_liescale", conn);

                MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                lbquestion.Content = cmd.ExecuteScalar(); //here I get the data into the label
            }
            catch (MySqlException ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                conn.Close();
            }
        }
    }

有没有办法在一个标签中显示数据库中的每条数据记录,并始终通过单击按钮用下一条记录覆盖它?

最佳答案

你应该使用 ExecuteReader()而不是 ExecuteScalar() 来检索数据集合。

StringBuilder sb = new StringBuilder();

using(var reader = cmd.ExecuteReader())
{
    while (reader.Read())
    {
        var question = reader[0].ToString();
        sb.AppendFormat("Q: {0}\n", question); // use any other format if needed
    }
}

lbquestion.Content = sb.ToString();

但更好的方法是使用ItemsControlListBox或其他列表控件。

如果你想通过点击按钮进行迭代,你可以将所有记录检索到内存中,然后在事件处理程序中进行迭代:

private readonly List<string> _questions;
private int currentIndex = -1;
public MainWindow()
{
    InitializeComponent();
    _questions = GetQuestionsByDataReader();
}

private void btContinue_Click(object sender, RoutedEventArgs e)
{
    if(currentIndex < _questions.Count)
    {
        lbquestion.Content = _questions[++currentIndex];
    }
}

关于具有多个事件的 C# 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36153552/

相关文章:

c# - 使用数据流调用起订量验证方法

c# - 当 List.property = myValue 时使用 Linq 删除列表项

java - mysql空指针异常

mysql - 向 MySQL 表添加大列(VARCHAR)会对性能产生重大影响吗?

sql - 如何从已计算的值中获取平均数

json - 在网站上显示大量数据的最有效方式是什么?

c# - 如何在不创 build 置的情况下让可执行文件在其他计算机上运行,

c# - WPF Datepicker 日历按钮不起作用(使用修改后的模板)

MySQL 按顺序获取父/子类别

php - 如何使用 PHP 或 mySQL 实现 2 路加密?