eCardProgrammer
eCardProgrammer

Reputation: 3

C# Button with multiple events

I am trying to overwrite a content in an label several times by always clicking the same button. Unfortunately, I only know how to override it once. The problem I am facing is that the data in the label are from an SQL database and it only displays the data with ID = 1 in the label.

This is my code:

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();
            }
        }
    }

Is there a way to display every data record from the database in one label and always overwriting it with the next record by clicking the button?

Upvotes: 0

Views: 55

Answers (1)

Vadim Martynov
Vadim Martynov

Reputation: 8902

You should use ExecuteReader() instead of ExecuteScalar() to retrieve collection of data.

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();

But the better way is to use ItemsControl or ListBox or other list-controls.

If you want to iterate by clicking the button you can retrieve all records to the memory and then iterate it in the event handler:

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];
    }
}

Upvotes: 3

Related Questions