0

I have a command that display the Name based on EmpID:

using (SqlCommand SqlCommand = new SqlCommand("Select EmpID, Name from EmpTable where EmpID = @a", myDatabaseConnection))
                {
                    SqlCommand.Parameters.AddWithValue("@a", textBox1.Text);
                    using (SqlDataReader sqlreader = SqlCommand.ExecuteReader())
                    {

                        if (sqlreader.Read())
                        {
                            Namelabel.Text = sqlreader.GetString(sqlreader.GetOrdinal("Name"));
                        }
                    }
                }

How I will handle if name data is null? Like if data is null Namelabel.Text = "".

3
  • What is there to handle? I would imagine the code you already have would work just fine if the output is null. Commented Jul 22, 2013 at 18:29
  • what do u want if its null? Commented Jul 22, 2013 at 18:30
  • What you want to check for null? Commented Jul 22, 2013 at 18:36

3 Answers 3

1

Do you mean something like this?

Namelabel.Text = !String.IsNullOrEmpty(sqlreader.GetString(sqlreader.GetOrdinal("Name"))) ? sqlreader.GetString(sqlreader.GetOrdinal("Name")) : "Value not found";

This will give some output if the value in the database is NULL.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use IsDBNull() to check for a null value before trying to read that value as a string. Something like this:

if (sqlreader.Read())
{
    var columnOrdinal = sqlreader.GetOrdinal("Name");
    if (sqlReader.IsDBNull(columnOrdinal))
        NameLabel.Text = string.Empty;
    else
        Namelabel.Text = sqlreader.GetString(columnOrdinal);
}

Comments

0

Just test for null as you read.

 if (sqlreader.Read())
 {
      Namelabel.Text = sqlreader.GetString(sqlreader.GetOrdinal("Name")==null?"":sqlreader.GetOrdinal("Name"));
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.