0

I need to help with displaying the data from the listbox output to the labels. In the listbox everything is loaded (I need to see Firstname and LastName) but it does not write anything on the labels - always an error.

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            connection.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = connection;
            string query = "SELECT * FROM Tab1 WHERE groupA='" + listBox1.Text + "' ORDER BY FirstName";
            command.CommandText = query;

            OleDbDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                listBox3.Items.Add(reader["FirstName"].ToString() + " " + reader["LastName"].ToString());
            }

            connection.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("ERROR" + ex);
        }
    }

listBox3_SelectedINdexChanged

private void listBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                connection.Open();
                OleDbCommand command = new OleDbCommand();
                command.Connection = connection;
                string query = "select * from Tab1 where FirstName=" + listBox2.Text + "";
                command.CommandText = query;

            OleDbDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                label6.Text = reader["FirstName"].ToString();
                label8.Text = reader["LastName"].ToString();
                label10.Text = reader["GroupPolice"].ToString();
            }

            connection.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("ERROR" + ex);
        }
    }

Thank you. enter image description here

Majid Parvin
  • 4,499
  • 5
  • 29
  • 47
VprogCS
  • 3
  • 2
  • `always an error.` Always tell us the error. – LarsTech Nov 11 '17 at 16:31
  • You have to use parameters to avoid sql injection and formatting errors, which is what is probably causing your issues. A label can only show one value, so a while-loop doesn't make sense. Use `if (reader.Read())` instead. – LarsTech Nov 11 '17 at 16:32

1 Answers1

0

Change the second query to:

string query = "select * from [Tab1] where FirstName='" + listBox2.Text + "'";

And while (reader.Read()) to:

 if (reader.Read())
Majid Parvin
  • 4,499
  • 5
  • 29
  • 47