Click here to Skip to main content
15,892,643 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How do I catch an empty reader.read an exception?
C#
private void KlantenContactInfo()
{
    const string queryKlantContactinfoID = "SELECT Naam, Telefoonnummer, Mobiel, Mail FROM KlantenContact WHERE IDKlantContactpersonen = @SELKlantcontactinfoID";

    using (SqlConnection connection = new SqlConnection(connectionstring))
    using (SqlCommand command = new SqlCommand(queryKlantContactinfoID, connection))
    {
        if (ListBoxKlanten.Items.Count == 0)
        {
            command.Parameters.AddWithValue("@SELKlantcontactinfoID", DBNull.Value);
        }
        else
        {
            command.Parameters.AddWithValue("@SELKlantcontactinfoID", listBoxKlantenContact.SelectedValue);
        }

        connection.Open();
        using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
        {
            //HELP
            if (reader.Read())
            {
                LB_KlantenContactNaam.Text = Convert.ToString(reader["Naam"]);
                LB_KlantenContactTelefoon.Text = Convert.ToString(reader["Telefoonnummer"]);
                LB_KlantenContactMobiel.Text = Convert.ToString(reader["Mobiel"]);
                LB_KlantenContactMail.Text = Convert.ToString(reader["Mail"]);
            }
        }
    }
}
Posted
Updated 15-Dec-15 23:35pm
v2

Your test:
C#
if (ListBoxKlanten.Items.Count == 0)
is insufficient.
In this case it's apparent that listBoxKlantenContact has values, but none is selected so listBoxKlantenContact.SelectedValue is null.

Try using
C#
command.Parameters.AddWithValue("@SELKlantcontactinfoID", listBoxKlantenContact.SelectedValue ?? DBNull.Value);
 
Share this answer
 
Try
C#
while (reader.Read()) {
   // ...
}

instead of
C#
if (reader.Read()) {
   // ...
}

Hope this helps.
 
Share this answer
 
Comments
MaikelO1 16-Dec-15 5:47am    
I already tried that. That is not the solution. Attached a screenshot of my fault that I get if ListBoxKlanten.Items.Count >1 and there are no results in reader.read ..

http://s4.postimg.org/fnstvloe5/Screen_Shot_2015_12_16_at_11_40_48.jpg
phil.o 16-Dec-15 6:03am    
Have you read the exception message to the right of the image? It is clearly descriptive.
Try
C#
if (reader.HasRows)
{
  reader.Read();
  //...
}


Or, the round-about way
C#
// In the SqlDataReader using block
using (DataTable results = new DataTable())
{
  results.Load(reader);
  if (results.Rows.Count > 0)
  {
    // map results to your fields
  }
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900