Conversion from type DBNull to type String is invalid

M

Michel Vanderbeke

Hello,

When reading data from a SqlClient.SqlDataReader in VB.NET 2005, I want to
display fiels that sometimes are empty.

sUser = CStr(rdUser("Name") & Space(1) & CStr(rdUser("First_Name")

When the First_Name of a user is empty, I get an error telling me type
DBNull cannot be converted to String.
Is there a way of solving this problem?

Many thanks,

Michel
 
R

rowe_newsgroups

Hello,

When reading data from a SqlClient.SqlDataReader in VB.NET 2005, I want to
display fiels that sometimes are empty.

sUser = CStr(rdUser("Name") & Space(1) & CStr(rdUser("First_Name")

When the First_Name of a user is empty, I get an error telling me type
DBNull cannot be converted to String.
Is there a way of solving this problem?

Many thanks,

Michel

Instead of:

sUser = CStr(rdUser("Name") & Space(1) & CStr(rdUser("First_Name")

Use:

sUser = rdUser("Name").ToString() & Space(1) & rdUser("First
Name")

or even better (imo):

sUser = String.Format("{0} {1}", rdUser("Name").ToString(),
rdUser("First_Name").ToString())


Thanks,

Seth Rowe
 
R

rowe_newsgroups

Instead of:

sUser = CStr(rdUser("Name") & Space(1) & CStr(rdUser("First_Name")

Use:

sUser = rdUser("Name").ToString() & Space(1) & rdUser("First
Name")

or even better (imo):

sUser = String.Format("{0} {1}", rdUser("Name").ToString(),
rdUser("First_Name").ToString())

Thanks,

Seth Rowe

sUser = rdUser("Name").ToString() & Space(1) & rdUser("First
Name")

That should be:

sUser = rdUser("Name").ToString() & Space(1) &
rdUser("First_Name").ToString()


Thanks,

Seth Rowe
 
H

Herfried K. Wagner [MVP]

rowe_newsgroups said:
Instead of:

sUser = CStr(rdUser("Name") & Space(1) & CStr(rdUser("First_Name")

Use:

sUser = rdUser("Name").ToString() & Space(1) & rdUser("First
Name")

or even better (imo):

sUser = String.Format("{0} {1}", rdUser("Name").ToString(),
rdUser("First_Name").ToString())


I am curious why this should be better. In addition, I'd write '... & " " &
....' instead of '... & Space(1) & ...'.
 
R

rowe_newsgroups

I am curious why this should be better. In addition, I'd write '... & " " &
...' instead of '... & Space(1) & ...'.

I never said it was better - I was referring to String.Format - I too
would use & " ". I just left the code as the OP had it for
consistency.

Thanks,

Seth Rowe
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top