Try something like this:
private void KlantenInfo()
{
const string queryKLantinfoID = "SELECT TOP 1 naam, Adres, Telefoon FROM Klanten WHERE [ID Klanten] = @SELKlantinfoID";
using (SqlConnection connection = new SqlConnection(connectionstring))
using (SqlCommand command = new SqlCommand(queryKLantinfoID, connection))
{
command.Parameters.AddWithValue("@SELKlantinfoID", ListBoxKlanten.SelectedValue);
connection.Open();
using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
{
if (reader.Read())
{
LB_KlantenNaam.Text = Convert.ToString(reader["naam"]);
LB_KlantenAdres.Text = Convert.ToString(reader["Adres"]);
LB_KlantenTelefoon.Text = Convert.ToString(reader["Telefoon"]);
}
else
{
LB_KlantenNaam.Text = string.Empty;
LB_KlantenAdres.Text = string.Empty;
LB_KlantenTelefoon.Text = string.Empty;
}
}
}
}
NB: You appear to be storing the
SqlConnection
in a field. That's a bad idea; instead, you should use a local variable in each method, as you have for the
SqlCommand
objects.
You should avoid using
SELECT * FROM ...
; only select the columns you're going to use.
I've added a
TOP 1
clause to your query, in case the
Klanten
column isn't the primary key. If it
is the primary key, you can omit this.
The
SqlDataReader
class has a
GetString
method which looks like it would work. Unfortunately, if the data returned from the database is
NULL
, this method throws a
SqlNullValueException
. You could use the
IsDBNull
method to test for this, but it's generally easier to use
Convert.ToString
on the raw value instead.