0

I have this short code which I use to read data into maskedtextbox and then (which isn't part of this code) UPDATE them via SqlCommand

    SqlCommand novyprikaz = new SqlCommand("SELECT * FROM zajezd WHERE akce=" + tentoradek, spojeni);
            spojeni.Open();
            SqlDataReader precti = novyprikaz.ExecuteReader();

            if (precti.Read())
            {maskedTextBox2.Text = precti.GetDateTime(24).ToShortDateString(); // i need to improve this part
}

But know if maskedTextBox2 value is NULL it gives me an error that:

Data is Null. This method or property cannot be called on Null values.

I would like to ask you, what should I change with this code to make it read Null? Thanks in advance.

Here is the snippet of the code which I used to do for INSERT INTO It is marked as an answer.

Marek
  • 3,555
  • 17
  • 74
  • 123

1 Answers1

1

Check if the SqlDataReader contains a DBNull value using the IsDBNull method on the column 24 and act appropriately returning an empty string or the not null value

 if (precti.Read())
 {

      maskedTextBox2.Text = precti.IsDBNull(24) ? 
                            string.Empty : 
                            precti.GetDateTime(24).ToShortDateString(); 
 }
Steve
  • 213,761
  • 22
  • 232
  • 286
  • Thanks so much for answering, but it gave me this error: Invalid attempt to read when no data is present. – Marek Jul 14 '13 at 14:12
  • That's strange because if the Read method returns true then you have advanced the reader on the first row and this means that a record exists. Then the IsDBNull checks if the column contains no value and only if it returns false the code tries to read the column 24. Have you other code before these lines that could change the behavior expected? – Steve Jul 14 '13 at 14:23