Null Values stopping code module.

G

Greg

I have the following three files.
1. Users.aspx is a webpage that uses the <asp:ObjectDataSource> control to
populate a simple <asp:ListBox> control.
2. The UserDetails.cs file creates a Namespace named UserComponents and
creates an object named UserDetails.
3. The UserDB.cs file retrieves the actual data from the database.

The code below has been condensed and only includes two fields from my
datasource. I actually am also
retrieving FirstName, MiddleName, etc. This code works fine as long as no
user has a UserName equal to
NULL. If any of the fields I include in the UserDetails object, I get the
following error on line 46.

Unable to cast object of type 'System.DBNull' to type 'System.String'.

Line 46: UserDetails user = new UserDetails((int)rdrUsers["UserID"],
Line 47:
(string)rdrUsers["UserName"],

I get the error regardless of what field is set as the <DataTextField>. If I
make sure all records have a
UserName not set to NULL the code works great. This can become a big problem
because in many cases
not every field will contain a value. I've thought I woudl just set the
default value of each field
to a blank space, as this will stop the error from happening, but I'm not so
sure I want to do this.

It seems to me this code should work with NULL values. NULL Values frustrate
me at times. Is there a way
I can make the code listed below work with NULL values? FYI: One of my
thoughts was to check for a NULL
value for each field, but this even doesn't sound like a good solution.

Can anyone provide some insight as to how I can make the following code work
when any of the source fields
may contain a NULL value?

Users.aspx (Web Page displaying listbox with UserNames)

<asp:ObjectDataSource
ID="sourceUsers" runat="server"
TypeName="UserComponents.UserDB" SelectMethod="GetUsers">
</asp:ObjectDataSource>
<asp:ListBox
ID="lstUserID" runat="server" DataSourceID="sourceUsers"
DataTextField="UserName" Width="224px">
</asp:ListBox>

UserDetails.cs (in App_Code folder)
namespace UserComponents
{
public class UserDetails
{
public int UserID
{
get { return m_userID; }
set { m_userID = value; }
}
public string UserName
{
get { return m_userName; }
set { m_userName = value; }
}

public UserDetails(int userID, string userName)
{
this.UserID = userID;
this.UserName = userName;
}
public UserDetails()
{
// Default Constructor
}
}
}
UserDB.cs (in App_Code folder)
namespace UserComponents
{
[DataObject]
public class UserDB
{
[DataObjectMethod(DataObjectMethodType.Select, true)]
public List<UserDetails> GetUsers()
{
SqlConnection sqlConn = new SqlConnection(m_strConn);
SqlCommand cmdUsers = new SqlCommand("sUsers", sqlConn);
cmdUsers.CommandType = CommandType.StoredProcedure;
// Create collection of all Users.
List<UserDetails> users = new List<UserDetails>();
try
{
sqlConn.Open();
SqlDataReader rdrUsers = cmdUsers.ExecuteReader();

while (rdrUsers.Read())
{
UserDetails user = new UserDetails( (int)rdrUsers["UserID"],
(string)rdrUsers["UserName"]);
users.Add(user);
}
rdrUsers.Close();
return users;
}
catch (SqlException ex)
{
throw new ApplicationException ("Error Occured");
}
finally
{
sqlConn.Close();
}
}
}
}}
 
C

Chuck D

You need to test the values for DBNull before using

String UserID = "";

if (rdrUsers["UserID"] = System.DBNull)
{UserID= "";}
else
{ UserID = rdrUsers["UserID"];}

There is an IsDBNull function on the reader, but I think it only takes an
ordinal, not a column name. I could be wrong on this. If I'm not wrong, you
can make your own function that takes the datareader value as input, and
returns a string using the above logic.

Greg said:
I have the following three files.
1. Users.aspx is a webpage that uses the <asp:ObjectDataSource> control to
populate a simple <asp:ListBox> control.
2. The UserDetails.cs file creates a Namespace named UserComponents and
creates an object named UserDetails.
3. The UserDB.cs file retrieves the actual data from the database.

The code below has been condensed and only includes two fields from my
datasource. I actually am also
retrieving FirstName, MiddleName, etc. This code works fine as long as no
user has a UserName equal to
NULL. If any of the fields I include in the UserDetails object, I get the
following error on line 46.

Unable to cast object of type 'System.DBNull' to type 'System.String'.

Line 46: UserDetails user = new UserDetails((int)rdrUsers["UserID"],
Line 47:
(string)rdrUsers["UserName"],

I get the error regardless of what field is set as the <DataTextField>. If I
make sure all records have a
UserName not set to NULL the code works great. This can become a big problem
because in many cases
not every field will contain a value. I've thought I woudl just set the
default value of each field
to a blank space, as this will stop the error from happening, but I'm not so
sure I want to do this.

It seems to me this code should work with NULL values. NULL Values frustrate
me at times. Is there a way
I can make the code listed below work with NULL values? FYI: One of my
thoughts was to check for a NULL
value for each field, but this even doesn't sound like a good solution.

Can anyone provide some insight as to how I can make the following code work
when any of the source fields
may contain a NULL value?

Users.aspx (Web Page displaying listbox with UserNames)

<asp:ObjectDataSource
ID="sourceUsers" runat="server"
TypeName="UserComponents.UserDB" SelectMethod="GetUsers">
</asp:ObjectDataSource>
<asp:ListBox
ID="lstUserID" runat="server" DataSourceID="sourceUsers"
DataTextField="UserName" Width="224px">
</asp:ListBox>

UserDetails.cs (in App_Code folder)
namespace UserComponents
{
public class UserDetails
{
public int UserID
{
get { return m_userID; }
set { m_userID = value; }
}
public string UserName
{
get { return m_userName; }
set { m_userName = value; }
}

public UserDetails(int userID, string userName)
{
this.UserID = userID;
this.UserName = userName;
}
public UserDetails()
{
// Default Constructor
}
}
}
UserDB.cs (in App_Code folder)
namespace UserComponents
{
[DataObject]
public class UserDB
{
[DataObjectMethod(DataObjectMethodType.Select, true)]
public List<UserDetails> GetUsers()
{
SqlConnection sqlConn = new SqlConnection(m_strConn);
SqlCommand cmdUsers = new SqlCommand("sUsers", sqlConn);
cmdUsers.CommandType = CommandType.StoredProcedure;
// Create collection of all Users.
List<UserDetails> users = new List<UserDetails>();
try
{
sqlConn.Open();
SqlDataReader rdrUsers = cmdUsers.ExecuteReader();

while (rdrUsers.Read())
{
UserDetails user = new UserDetails( (int)rdrUsers["UserID"],
(string)rdrUsers["UserName"]);
users.Add(user);
}
rdrUsers.Close();
return users;
}
catch (SqlException ex)
{
throw new ApplicationException ("Error Occured");
}
finally
{
sqlConn.Close();
}
}
}
}}
 
C

Chuck D

typo alert:

if (rdrUsers["UserID"] == System.DBNull)
{UserID= "";}
else
{ UserID = rdrUsers["UserID"];}


Chuck D said:
You need to test the values for DBNull before using

String UserID = "";

if (rdrUsers["UserID"] = System.DBNull)
{UserID= "";}
else
{ UserID = rdrUsers["UserID"];}

There is an IsDBNull function on the reader, but I think it only takes an
ordinal, not a column name. I could be wrong on this. If I'm not wrong, you
can make your own function that takes the datareader value as input, and
returns a string using the above logic.

Greg said:
I have the following three files.
1. Users.aspx is a webpage that uses the <asp:ObjectDataSource> control to
populate a simple <asp:ListBox> control.
2. The UserDetails.cs file creates a Namespace named UserComponents and
creates an object named UserDetails.
3. The UserDB.cs file retrieves the actual data from the database.

The code below has been condensed and only includes two fields from my
datasource. I actually am also
retrieving FirstName, MiddleName, etc. This code works fine as long as no
user has a UserName equal to
NULL. If any of the fields I include in the UserDetails object, I get the
following error on line 46.

Unable to cast object of type 'System.DBNull' to type 'System.String'.

Line 46: UserDetails user = new UserDetails((int)rdrUsers["UserID"],
Line 47:
(string)rdrUsers["UserName"],

I get the error regardless of what field is set as the <DataTextField>. If I
make sure all records have a
UserName not set to NULL the code works great. This can become a big problem
because in many cases
not every field will contain a value. I've thought I woudl just set the
default value of each field
to a blank space, as this will stop the error from happening, but I'm not so
sure I want to do this.

It seems to me this code should work with NULL values. NULL Values frustrate
me at times. Is there a way
I can make the code listed below work with NULL values? FYI: One of my
thoughts was to check for a NULL
value for each field, but this even doesn't sound like a good solution.

Can anyone provide some insight as to how I can make the following code work
when any of the source fields
may contain a NULL value?

Users.aspx (Web Page displaying listbox with UserNames)

<asp:ObjectDataSource
ID="sourceUsers" runat="server"
TypeName="UserComponents.UserDB" SelectMethod="GetUsers">
</asp:ObjectDataSource>
<asp:ListBox
ID="lstUserID" runat="server" DataSourceID="sourceUsers"
DataTextField="UserName" Width="224px">
</asp:ListBox>

UserDetails.cs (in App_Code folder)
namespace UserComponents
{
public class UserDetails
{
public int UserID
{
get { return m_userID; }
set { m_userID = value; }
}
public string UserName
{
get { return m_userName; }
set { m_userName = value; }
}

public UserDetails(int userID, string userName)
{
this.UserID = userID;
this.UserName = userName;
}
public UserDetails()
{
// Default Constructor
}
}
}
UserDB.cs (in App_Code folder)
namespace UserComponents
{
[DataObject]
public class UserDB
{
[DataObjectMethod(DataObjectMethodType.Select, true)]
public List<UserDetails> GetUsers()
{
SqlConnection sqlConn = new SqlConnection(m_strConn);
SqlCommand cmdUsers = new SqlCommand("sUsers", sqlConn);
cmdUsers.CommandType = CommandType.StoredProcedure;
// Create collection of all Users.
List<UserDetails> users = new List<UserDetails>();
try
{
sqlConn.Open();
SqlDataReader rdrUsers = cmdUsers.ExecuteReader();

while (rdrUsers.Read())
{
UserDetails user = new UserDetails( (int)rdrUsers["UserID"],
(string)rdrUsers["UserName"]);
users.Add(user);
}
rdrUsers.Close();
return users;
}
catch (SqlException ex)
{
throw new ApplicationException ("Error Occured");
}
finally
{
sqlConn.Close();
}
}
}
}}
 
G

Greg

Chuck,

I tried something along the line of what you provided. I got the same error
that I am getting with this sample as well. Here is what I added to my source
code. In this case, I am checking the value of a field named: "password".

string password = "";
if (rdrUsers["Password"] == System.DBNull)
{ password = ""; }
else
{ password = rdrUsers["Password"]; }

I get the following error message when I initially start my web application,
before even getting to the page that uses this code module.

CS0119: 'System.DBNull' is a 'type', which is not valid in the given context

Any ideas?


Chuck D said:
typo alert:

if (rdrUsers["UserID"] == System.DBNull)
{UserID= "";}
else
{ UserID = rdrUsers["UserID"];}


Chuck D said:
You need to test the values for DBNull before using

String UserID = "";

if (rdrUsers["UserID"] = System.DBNull)
{UserID= "";}
else
{ UserID = rdrUsers["UserID"];}

There is an IsDBNull function on the reader, but I think it only takes an
ordinal, not a column name. I could be wrong on this. If I'm not wrong, you
can make your own function that takes the datareader value as input, and
returns a string using the above logic.

Greg said:
I have the following three files.
1. Users.aspx is a webpage that uses the <asp:ObjectDataSource> control to
populate a simple <asp:ListBox> control.
2. The UserDetails.cs file creates a Namespace named UserComponents and
creates an object named UserDetails.
3. The UserDB.cs file retrieves the actual data from the database.

The code below has been condensed and only includes two fields from my
datasource. I actually am also
retrieving FirstName, MiddleName, etc. This code works fine as long as no
user has a UserName equal to
NULL. If any of the fields I include in the UserDetails object, I get the
following error on line 46.

Unable to cast object of type 'System.DBNull' to type 'System.String'.

Line 46: UserDetails user = new UserDetails((int)rdrUsers["UserID"],
Line 47:
(string)rdrUsers["UserName"],

I get the error regardless of what field is set as the <DataTextField>. If I
make sure all records have a
UserName not set to NULL the code works great. This can become a big problem
because in many cases
not every field will contain a value. I've thought I woudl just set the
default value of each field
to a blank space, as this will stop the error from happening, but I'm not so
sure I want to do this.

It seems to me this code should work with NULL values. NULL Values frustrate
me at times. Is there a way
I can make the code listed below work with NULL values? FYI: One of my
thoughts was to check for a NULL
value for each field, but this even doesn't sound like a good solution.

Can anyone provide some insight as to how I can make the following code work
when any of the source fields
may contain a NULL value?

Users.aspx (Web Page displaying listbox with UserNames)

<asp:ObjectDataSource
ID="sourceUsers" runat="server"
TypeName="UserComponents.UserDB" SelectMethod="GetUsers">
</asp:ObjectDataSource>
<asp:ListBox
ID="lstUserID" runat="server" DataSourceID="sourceUsers"
DataTextField="UserName" Width="224px">
</asp:ListBox>

UserDetails.cs (in App_Code folder)
namespace UserComponents
{
public class UserDetails
{
public int UserID
{
get { return m_userID; }
set { m_userID = value; }
}
public string UserName
{
get { return m_userName; }
set { m_userName = value; }
}

public UserDetails(int userID, string userName)
{
this.UserID = userID;
this.UserName = userName;
}
public UserDetails()
{
// Default Constructor
}
}
}
UserDB.cs (in App_Code folder)
namespace UserComponents
{
[DataObject]
public class UserDB
{
[DataObjectMethod(DataObjectMethodType.Select, true)]
public List<UserDetails> GetUsers()
{
SqlConnection sqlConn = new SqlConnection(m_strConn);
SqlCommand cmdUsers = new SqlCommand("sUsers", sqlConn);
cmdUsers.CommandType = CommandType.StoredProcedure;
// Create collection of all Users.
List<UserDetails> users = new List<UserDetails>();
try
{
sqlConn.Open();
SqlDataReader rdrUsers = cmdUsers.ExecuteReader();

while (rdrUsers.Read())
{
UserDetails user = new UserDetails( (int)rdrUsers["UserID"],
(string)rdrUsers["UserName"]);
users.Add(user);
}
rdrUsers.Close();
return users;
}
catch (SqlException ex)
{
throw new ApplicationException ("Error Occured");
}
finally
{
sqlConn.Close();
}
}
}
}}
 
R

Ralph

Chuck,

I tried something along the line of what you provided. I got the same error
that I am getting with this sample as well. Here is what I added to my source
code. In this case, I am checking the value of a field named: "password".

          string password = "";
          if (rdrUsers["Password"] == System.DBNull)
            { password = ""; }
          else
            { password = rdrUsers["Password"]; }

I get the following error message when I initially start my web application,
before even getting to the page that uses this code module.

CS0119: 'System.DBNull' is a 'type', which is not valid in the given context

Any ideas?



Chuck D said:
typo alert:
 if (rdrUsers["UserID"] == System.DBNull)
             {UserID= "";}
             else
             { UserID = rdrUsers["UserID"];}
You need to test the values for DBNull before using
            String UserID = "";
            if (rdrUsers["UserID"] = System.DBNull)
            {UserID= "";}
            else
            { UserID = rdrUsers["UserID"];}
There is an IsDBNull function on the reader, but I think it only takes an
ordinal, not a column name.  I could be wrong on this. If I'm not wrong, you
can make your own function that takes the datareader value as input, and
returns a string using the above logic.
:
I have the following three files.
1. Users.aspx is a webpage that uses the <asp:ObjectDataSource> control to
populate a simple <asp:ListBox> control.
2. The UserDetails.cs file creates a Namespace named UserComponentsand
creates an object named UserDetails.
3. The UserDB.cs file retrieves the actual data from the database.
The code below has been condensed and only includes two fields frommy
datasource. I actually am also
retrieving FirstName, MiddleName, etc. This code works fine as longas no
user has a UserName equal to
NULL. If any of the fields I include in the UserDetails object, I get the
following error on line 46.
Unable to cast object of type 'System.DBNull' to type 'System.String'.
Line 46:           UserDetails user = new UserDetails((int)rdrUsers["UserID"],
Line 47:                                              
(string)rdrUsers["UserName"],
I get the error regardless of what field is set as the <DataTextField>. If I
make sure all records have a
UserName not set to NULL the code works great. This can become a big problem
because in many cases
not every field will contain a value. I've thought I woudl just setthe
default value of each field
to a blank space, as this will stop the error from happening, but I'm not so
sure I want to do this.
It seems to me this code should work with NULL values. NULL Values frustrate
me at times. Is there a way
I can make the code listed below work with NULL values? FYI: One ofmy
thoughts was to check for a NULL
value for each field, but this even doesn't sound like a good solution.
Can anyone provide some insight as to how I can make the following code work
when any of the source fields
may contain a NULL value?
Users.aspx (Web Page displaying listbox with UserNames)
  <asp:ObjectDataSource
    ID="sourceUsers" runat="server"
    TypeName="UserComponents.UserDB" SelectMethod="GetUsers">
  </asp:ObjectDataSource>
  <asp:ListBox
    ID="lstUserID" runat="server" DataSourceID="sourceUsers"
    DataTextField="UserName" Width="224px">
  </asp:ListBox>
UserDetails.cs (in App_Code folder)
namespace UserComponents
{
  public class UserDetails
  {
    public int UserID
    {
      get { return m_userID; }
      set { m_userID = value; }
    }
    public string UserName
    {
      get { return m_userName; }
      set { m_userName = value; }
    }
    public UserDetails(int userID, string userName)
    {
      this.UserID = userID;
      this.UserName = userName;
    }
    public UserDetails()
    {
    // Default Constructor
    }
  }
}
UserDB.cs (in App_Code folder)
namespace UserComponents
{
  [DataObject]
  public class UserDB
  {
    [DataObjectMethod(DataObjectMethodType.Select, true)]
    public List<UserDetails> GetUsers()
    {
      SqlConnection sqlConn = new SqlConnection(m_strConn);
      SqlCommand cmdUsers = new SqlCommand("sUsers", sqlConn);
      cmdUsers.CommandType = CommandType.StoredProcedure;    
      // Create collection of all Users.
      List<UserDetails> users = new List<UserDetails>();
      try
      {
        sqlConn.Open();
        SqlDataReader rdrUsers = cmdUsers.ExecuteReader();
        while (rdrUsers.Read())
        {
          UserDetails user = new UserDetails( (int)rdrUsers["UserID"],
                                             (string)rdrUsers["UserName"]);
          users.Add(user);
        }
        rdrUsers.Close();
        return users;
      }
      catch (SqlException ex)
      {
        throw new ApplicationException ("Error Occured");
      }
      finally
      {
        sqlConn.Close();
      }
    }
  }
}}- Hide quoted text -

- Show quoted text -

System.DBNull.value
 
G

gerry

use rdrUsers["UserID"] == System.DBNull.Value
or use System.DBNull.Equals( rdrUsers["UserID"] )


Greg said:
Chuck,

I tried something along the line of what you provided. I got the same
error
that I am getting with this sample as well. Here is what I added to my
source
code. In this case, I am checking the value of a field named: "password".

string password = "";
if (rdrUsers["Password"] == System.DBNull)
{ password = ""; }
else
{ password = rdrUsers["Password"]; }

I get the following error message when I initially start my web
application,
before even getting to the page that uses this code module.

CS0119: 'System.DBNull' is a 'type', which is not valid in the given
context

Any ideas?


Chuck D said:
typo alert:

if (rdrUsers["UserID"] == System.DBNull)
{UserID= "";}
else
{ UserID = rdrUsers["UserID"];}


Chuck D said:
You need to test the values for DBNull before using

String UserID = "";

if (rdrUsers["UserID"] = System.DBNull)
{UserID= "";}
else
{ UserID = rdrUsers["UserID"];}

There is an IsDBNull function on the reader, but I think it only takes
an
ordinal, not a column name. I could be wrong on this. If I'm not
wrong, you
can make your own function that takes the datareader value as input,
and
returns a string using the above logic.

:

I have the following three files.
1. Users.aspx is a webpage that uses the <asp:ObjectDataSource>
control to
populate a simple <asp:ListBox> control.
2. The UserDetails.cs file creates a Namespace named UserComponents
and
creates an object named UserDetails.
3. The UserDB.cs file retrieves the actual data from the database.

The code below has been condensed and only includes two fields from
my
datasource. I actually am also
retrieving FirstName, MiddleName, etc. This code works fine as long
as no
user has a UserName equal to
NULL. If any of the fields I include in the UserDetails object, I get
the
following error on line 46.

Unable to cast object of type 'System.DBNull' to type
'System.String'.

Line 46: UserDetails user = new
UserDetails((int)rdrUsers["UserID"],
Line 47:
(string)rdrUsers["UserName"],

I get the error regardless of what field is set as the
<DataTextField>. If I
make sure all records have a
UserName not set to NULL the code works great. This can become a big
problem
because in many cases
not every field will contain a value. I've thought I woudl just set
the
default value of each field
to a blank space, as this will stop the error from happening, but I'm
not so
sure I want to do this.

It seems to me this code should work with NULL values. NULL Values
frustrate
me at times. Is there a way
I can make the code listed below work with NULL values? FYI: One of
my
thoughts was to check for a NULL
value for each field, but this even doesn't sound like a good
solution.

Can anyone provide some insight as to how I can make the following
code work
when any of the source fields
may contain a NULL value?

Users.aspx (Web Page displaying listbox with UserNames)

<asp:ObjectDataSource
ID="sourceUsers" runat="server"
TypeName="UserComponents.UserDB" SelectMethod="GetUsers">
</asp:ObjectDataSource>
<asp:ListBox
ID="lstUserID" runat="server" DataSourceID="sourceUsers"
DataTextField="UserName" Width="224px">
</asp:ListBox>

UserDetails.cs (in App_Code folder)
namespace UserComponents
{
public class UserDetails
{
public int UserID
{
get { return m_userID; }
set { m_userID = value; }
}
public string UserName
{
get { return m_userName; }
set { m_userName = value; }
}

public UserDetails(int userID, string userName)
{
this.UserID = userID;
this.UserName = userName;
}
public UserDetails()
{
// Default Constructor
}
}
}
UserDB.cs (in App_Code folder)
namespace UserComponents
{
[DataObject]
public class UserDB
{
[DataObjectMethod(DataObjectMethodType.Select, true)]
public List<UserDetails> GetUsers()
{
SqlConnection sqlConn = new SqlConnection(m_strConn);
SqlCommand cmdUsers = new SqlCommand("sUsers", sqlConn);
cmdUsers.CommandType = CommandType.StoredProcedure;
// Create collection of all Users.
List<UserDetails> users = new List<UserDetails>();
try
{
sqlConn.Open();
SqlDataReader rdrUsers = cmdUsers.ExecuteReader();

while (rdrUsers.Read())
{
UserDetails user = new UserDetails(
(int)rdrUsers["UserID"],

(string)rdrUsers["UserName"]);
users.Add(user);
}
rdrUsers.Close();
return users;
}
catch (SqlException ex)
{
throw new ApplicationException ("Error Occured");
}
finally
{
sqlConn.Close();
}
}
}
}}
 
C

Chuck D

My Bad, should be:

The compiler is correctly reporting that we were trying to compare a value
to a type.

Chuck
string password = "";
if (rdrUsers["Password"] == System.DBNull.Value)
{ password = ""; }
else
{ password = rdrUsers["Password"]; }

Greg said:
Chuck,

I tried something along the line of what you provided. I got the same error
that I am getting with this sample as well. Here is what I added to my source
code. In this case, I am checking the value of a field named: "password".

string password = "";
if (rdrUsers["Password"] == System.DBNull)
{ password = ""; }
else
{ password = rdrUsers["Password"]; }

I get the following error message when I initially start my web application,
before even getting to the page that uses this code module.

CS0119: 'System.DBNull' is a 'type', which is not valid in the given context

Any ideas?


Chuck D said:
typo alert:

if (rdrUsers["UserID"] == System.DBNull)
{UserID= "";}
else
{ UserID = rdrUsers["UserID"];}


Chuck D said:
You need to test the values for DBNull before using

String UserID = "";

if (rdrUsers["UserID"] = System.DBNull)
{UserID= "";}
else
{ UserID = rdrUsers["UserID"];}

There is an IsDBNull function on the reader, but I think it only takes an
ordinal, not a column name. I could be wrong on this. If I'm not wrong, you
can make your own function that takes the datareader value as input, and
returns a string using the above logic.

:

I have the following three files.
1. Users.aspx is a webpage that uses the <asp:ObjectDataSource> control to
populate a simple <asp:ListBox> control.
2. The UserDetails.cs file creates a Namespace named UserComponents and
creates an object named UserDetails.
3. The UserDB.cs file retrieves the actual data from the database.

The code below has been condensed and only includes two fields from my
datasource. I actually am also
retrieving FirstName, MiddleName, etc. This code works fine as long as no
user has a UserName equal to
NULL. If any of the fields I include in the UserDetails object, I get the
following error on line 46.

Unable to cast object of type 'System.DBNull' to type 'System.String'.

Line 46: UserDetails user = new UserDetails((int)rdrUsers["UserID"],
Line 47:
(string)rdrUsers["UserName"],

I get the error regardless of what field is set as the <DataTextField>. If I
make sure all records have a
UserName not set to NULL the code works great. This can become a big problem
because in many cases
not every field will contain a value. I've thought I woudl just set the
default value of each field
to a blank space, as this will stop the error from happening, but I'm not so
sure I want to do this.

It seems to me this code should work with NULL values. NULL Values frustrate
me at times. Is there a way
I can make the code listed below work with NULL values? FYI: One of my
thoughts was to check for a NULL
value for each field, but this even doesn't sound like a good solution.

Can anyone provide some insight as to how I can make the following code work
when any of the source fields
may contain a NULL value?

Users.aspx (Web Page displaying listbox with UserNames)

<asp:ObjectDataSource
ID="sourceUsers" runat="server"
TypeName="UserComponents.UserDB" SelectMethod="GetUsers">
</asp:ObjectDataSource>
<asp:ListBox
ID="lstUserID" runat="server" DataSourceID="sourceUsers"
DataTextField="UserName" Width="224px">
</asp:ListBox>

UserDetails.cs (in App_Code folder)
namespace UserComponents
{
public class UserDetails
{
public int UserID
{
get { return m_userID; }
set { m_userID = value; }
}
public string UserName
{
get { return m_userName; }
set { m_userName = value; }
}

public UserDetails(int userID, string userName)
{
this.UserID = userID;
this.UserName = userName;
}
public UserDetails()
{
// Default Constructor
}
}
}
UserDB.cs (in App_Code folder)
namespace UserComponents
{
[DataObject]
public class UserDB
{
[DataObjectMethod(DataObjectMethodType.Select, true)]
public List<UserDetails> GetUsers()
{
SqlConnection sqlConn = new SqlConnection(m_strConn);
SqlCommand cmdUsers = new SqlCommand("sUsers", sqlConn);
cmdUsers.CommandType = CommandType.StoredProcedure;
// Create collection of all Users.
List<UserDetails> users = new List<UserDetails>();
try
{
sqlConn.Open();
SqlDataReader rdrUsers = cmdUsers.ExecuteReader();

while (rdrUsers.Read())
{
UserDetails user = new UserDetails( (int)rdrUsers["UserID"],
(string)rdrUsers["UserName"]);
users.Add(user);
}
rdrUsers.Close();
return users;
}
catch (SqlException ex)
{
throw new ApplicationException ("Error Occured");
}
finally
{
sqlConn.Close();
}
}
}
}}
 
J

Jeff Johnson

string password = "";
if (rdrUsers["Password"] == System.DBNull.Value)
{ password = ""; }
else
{ password = rdrUsers["Password"]; }

Since you've already set password to the empty string on declaration, why
not only set it again if you have a value:

string password = "";
if (rdrUsers["Password"] != System.DBNull.Value)
{
password = rdrUsers["Password"].ToString();
}

And isn't the ToString() required as well?
 
G

Greg

That does the trick. Thanks so much.

Chuck D said:
My Bad, should be:

The compiler is correctly reporting that we were trying to compare a value
to a type.

Chuck
string password = "";
if (rdrUsers["Password"] == System.DBNull.Value)
{ password = ""; }
else
{ password = rdrUsers["Password"]; }

Greg said:
Chuck,

I tried something along the line of what you provided. I got the same error
that I am getting with this sample as well. Here is what I added to my source
code. In this case, I am checking the value of a field named: "password".

string password = "";
if (rdrUsers["Password"] == System.DBNull)
{ password = ""; }
else
{ password = rdrUsers["Password"]; }

I get the following error message when I initially start my web application,
before even getting to the page that uses this code module.

CS0119: 'System.DBNull' is a 'type', which is not valid in the given context

Any ideas?


Chuck D said:
typo alert:

if (rdrUsers["UserID"] == System.DBNull)
{UserID= "";}
else
{ UserID = rdrUsers["UserID"];}


:

You need to test the values for DBNull before using

String UserID = "";

if (rdrUsers["UserID"] = System.DBNull)
{UserID= "";}
else
{ UserID = rdrUsers["UserID"];}

There is an IsDBNull function on the reader, but I think it only takes an
ordinal, not a column name. I could be wrong on this. If I'm not wrong, you
can make your own function that takes the datareader value as input, and
returns a string using the above logic.

:

I have the following three files.
1. Users.aspx is a webpage that uses the <asp:ObjectDataSource> control to
populate a simple <asp:ListBox> control.
2. The UserDetails.cs file creates a Namespace named UserComponents and
creates an object named UserDetails.
3. The UserDB.cs file retrieves the actual data from the database.

The code below has been condensed and only includes two fields from my
datasource. I actually am also
retrieving FirstName, MiddleName, etc. This code works fine as long as no
user has a UserName equal to
NULL. If any of the fields I include in the UserDetails object, I get the
following error on line 46.

Unable to cast object of type 'System.DBNull' to type 'System.String'.

Line 46: UserDetails user = new UserDetails((int)rdrUsers["UserID"],
Line 47:
(string)rdrUsers["UserName"],

I get the error regardless of what field is set as the <DataTextField>. If I
make sure all records have a
UserName not set to NULL the code works great. This can become a big problem
because in many cases
not every field will contain a value. I've thought I woudl just set the
default value of each field
to a blank space, as this will stop the error from happening, but I'm not so
sure I want to do this.

It seems to me this code should work with NULL values. NULL Values frustrate
me at times. Is there a way
I can make the code listed below work with NULL values? FYI: One of my
thoughts was to check for a NULL
value for each field, but this even doesn't sound like a good solution.

Can anyone provide some insight as to how I can make the following code work
when any of the source fields
may contain a NULL value?

Users.aspx (Web Page displaying listbox with UserNames)

<asp:ObjectDataSource
ID="sourceUsers" runat="server"
TypeName="UserComponents.UserDB" SelectMethod="GetUsers">
</asp:ObjectDataSource>
<asp:ListBox
ID="lstUserID" runat="server" DataSourceID="sourceUsers"
DataTextField="UserName" Width="224px">
</asp:ListBox>

UserDetails.cs (in App_Code folder)
namespace UserComponents
{
public class UserDetails
{
public int UserID
{
get { return m_userID; }
set { m_userID = value; }
}
public string UserName
{
get { return m_userName; }
set { m_userName = value; }
}

public UserDetails(int userID, string userName)
{
this.UserID = userID;
this.UserName = userName;
}
public UserDetails()
{
// Default Constructor
}
}
}
UserDB.cs (in App_Code folder)
namespace UserComponents
{
[DataObject]
public class UserDB
{
[DataObjectMethod(DataObjectMethodType.Select, true)]
public List<UserDetails> GetUsers()
{
SqlConnection sqlConn = new SqlConnection(m_strConn);
SqlCommand cmdUsers = new SqlCommand("sUsers", sqlConn);
cmdUsers.CommandType = CommandType.StoredProcedure;
// Create collection of all Users.
List<UserDetails> users = new List<UserDetails>();
try
{
sqlConn.Open();
SqlDataReader rdrUsers = cmdUsers.ExecuteReader();

while (rdrUsers.Read())
{
UserDetails user = new UserDetails( (int)rdrUsers["UserID"],
(string)rdrUsers["UserName"]);
users.Add(user);
}
rdrUsers.Close();
return users;
}
catch (SqlException ex)
{
throw new ApplicationException ("Error Occured");
}
finally
{
sqlConn.Close();
}
}
}
}}
 
G

Greg

In my Code Behind file this code works great. I'm thinking down the road I'd
like this to be handled in my Data/Property Class instead, thus I would not
have to always worry about these situations on every page. I think in the
long run this would be a huge task to have to handle on every single page.

So, I tried to do the following, thinking it will return "---" when the
value is NULL.

public string Prefix
{
get { return m_prefix; }
set
{
if (value == System.DBNull.Value)
{ m_prefix = "---"; }
else
{ m_prefix = value; }
}
}

But, I cannot do this as it reports an error. It states that the
System.DBNull.Value is a field but is treated a a "type"

Is it possible for me to handle this situation like I want? Or, do I need to
stick with what you've originally proposed?

Thanks again for you help.

Chuck D said:
My Bad, should be:

The compiler is correctly reporting that we were trying to compare a value
to a type.

Chuck
string password = "";
if (rdrUsers["Password"] == System.DBNull.Value)
{ password = ""; }
else
{ password = rdrUsers["Password"]; }

Greg said:
Chuck,

I tried something along the line of what you provided. I got the same error
that I am getting with this sample as well. Here is what I added to my source
code. In this case, I am checking the value of a field named: "password".

string password = "";
if (rdrUsers["Password"] == System.DBNull)
{ password = ""; }
else
{ password = rdrUsers["Password"]; }

I get the following error message when I initially start my web application,
before even getting to the page that uses this code module.

CS0119: 'System.DBNull' is a 'type', which is not valid in the given context

Any ideas?


Chuck D said:
typo alert:

if (rdrUsers["UserID"] == System.DBNull)
{UserID= "";}
else
{ UserID = rdrUsers["UserID"];}


:

You need to test the values for DBNull before using

String UserID = "";

if (rdrUsers["UserID"] = System.DBNull)
{UserID= "";}
else
{ UserID = rdrUsers["UserID"];}

There is an IsDBNull function on the reader, but I think it only takes an
ordinal, not a column name. I could be wrong on this. If I'm not wrong, you
can make your own function that takes the datareader value as input, and
returns a string using the above logic.

:

I have the following three files.
1. Users.aspx is a webpage that uses the <asp:ObjectDataSource> control to
populate a simple <asp:ListBox> control.
2. The UserDetails.cs file creates a Namespace named UserComponents and
creates an object named UserDetails.
3. The UserDB.cs file retrieves the actual data from the database.

The code below has been condensed and only includes two fields from my
datasource. I actually am also
retrieving FirstName, MiddleName, etc. This code works fine as long as no
user has a UserName equal to
NULL. If any of the fields I include in the UserDetails object, I get the
following error on line 46.

Unable to cast object of type 'System.DBNull' to type 'System.String'.

Line 46: UserDetails user = new UserDetails((int)rdrUsers["UserID"],
Line 47:
(string)rdrUsers["UserName"],

I get the error regardless of what field is set as the <DataTextField>. If I
make sure all records have a
UserName not set to NULL the code works great. This can become a big problem
because in many cases
not every field will contain a value. I've thought I woudl just set the
default value of each field
to a blank space, as this will stop the error from happening, but I'm not so
sure I want to do this.

It seems to me this code should work with NULL values. NULL Values frustrate
me at times. Is there a way
I can make the code listed below work with NULL values? FYI: One of my
thoughts was to check for a NULL
value for each field, but this even doesn't sound like a good solution.

Can anyone provide some insight as to how I can make the following code work
when any of the source fields
may contain a NULL value?

Users.aspx (Web Page displaying listbox with UserNames)

<asp:ObjectDataSource
ID="sourceUsers" runat="server"
TypeName="UserComponents.UserDB" SelectMethod="GetUsers">
</asp:ObjectDataSource>
<asp:ListBox
ID="lstUserID" runat="server" DataSourceID="sourceUsers"
DataTextField="UserName" Width="224px">
</asp:ListBox>

UserDetails.cs (in App_Code folder)
namespace UserComponents
{
public class UserDetails
{
public int UserID
{
get { return m_userID; }
set { m_userID = value; }
}
public string UserName
{
get { return m_userName; }
set { m_userName = value; }
}

public UserDetails(int userID, string userName)
{
this.UserID = userID;
this.UserName = userName;
}
public UserDetails()
{
// Default Constructor
}
}
}
UserDB.cs (in App_Code folder)
namespace UserComponents
{
[DataObject]
public class UserDB
{
[DataObjectMethod(DataObjectMethodType.Select, true)]
public List<UserDetails> GetUsers()
{
SqlConnection sqlConn = new SqlConnection(m_strConn);
SqlCommand cmdUsers = new SqlCommand("sUsers", sqlConn);
cmdUsers.CommandType = CommandType.StoredProcedure;
// Create collection of all Users.
List<UserDetails> users = new List<UserDetails>();
try
{
sqlConn.Open();
SqlDataReader rdrUsers = cmdUsers.ExecuteReader();

while (rdrUsers.Read())
{
UserDetails user = new UserDetails( (int)rdrUsers["UserID"],
(string)rdrUsers["UserName"]);
users.Add(user);
}
rdrUsers.Close();
return users;
}
catch (SqlException ex)
{
throw new ApplicationException ("Error Occured");
}
finally
{
sqlConn.Close();
}
}
}
}}
 
C

Chuck D

Hi Greg,

Obviously I'm not the sharpest tack in the box, as it took me three posts to
get you the right code to do a null test before using a datareader value.

I will say this though...

System.DBNull.Value is a data tier concept, and as such should not percolate
up into your classes property setters.

The safest path is to not pull the trigger on a set for a property at all if
the value is System.DBNull.Value. Going down the road of introducing your own
concept of null '---' is not the way to go.

Chuck

Greg said:
In my Code Behind file this code works great. I'm thinking down the road I'd
like this to be handled in my Data/Property Class instead, thus I would not
have to always worry about these situations on every page. I think in the
long run this would be a huge task to have to handle on every single page.

So, I tried to do the following, thinking it will return "---" when the
value is NULL.

public string Prefix
{
get { return m_prefix; }
set
{
if (value == System.DBNull.Value)
{ m_prefix = "---"; }
else
{ m_prefix = value; }
}
}

But, I cannot do this as it reports an error. It states that the
System.DBNull.Value is a field but is treated a a "type"

Is it possible for me to handle this situation like I want? Or, do I need to
stick with what you've originally proposed?

Thanks again for you help.

Chuck D said:
My Bad, should be:

The compiler is correctly reporting that we were trying to compare a value
to a type.

Chuck
string password = "";
if (rdrUsers["Password"] == System.DBNull.Value)
{ password = ""; }
else
{ password = rdrUsers["Password"]; }

Greg said:
Chuck,

I tried something along the line of what you provided. I got the same error
that I am getting with this sample as well. Here is what I added to my source
code. In this case, I am checking the value of a field named: "password".

string password = "";
if (rdrUsers["Password"] == System.DBNull)
{ password = ""; }
else
{ password = rdrUsers["Password"]; }

I get the following error message when I initially start my web application,
before even getting to the page that uses this code module.

CS0119: 'System.DBNull' is a 'type', which is not valid in the given context

Any ideas?


:

typo alert:

if (rdrUsers["UserID"] == System.DBNull)
{UserID= "";}
else
{ UserID = rdrUsers["UserID"];}


:

You need to test the values for DBNull before using

String UserID = "";

if (rdrUsers["UserID"] = System.DBNull)
{UserID= "";}
else
{ UserID = rdrUsers["UserID"];}

There is an IsDBNull function on the reader, but I think it only takes an
ordinal, not a column name. I could be wrong on this. If I'm not wrong, you
can make your own function that takes the datareader value as input, and
returns a string using the above logic.

:

I have the following three files.
1. Users.aspx is a webpage that uses the <asp:ObjectDataSource> control to
populate a simple <asp:ListBox> control.
2. The UserDetails.cs file creates a Namespace named UserComponents and
creates an object named UserDetails.
3. The UserDB.cs file retrieves the actual data from the database.

The code below has been condensed and only includes two fields from my
datasource. I actually am also
retrieving FirstName, MiddleName, etc. This code works fine as long as no
user has a UserName equal to
NULL. If any of the fields I include in the UserDetails object, I get the
following error on line 46.

Unable to cast object of type 'System.DBNull' to type 'System.String'.

Line 46: UserDetails user = new UserDetails((int)rdrUsers["UserID"],
Line 47:
(string)rdrUsers["UserName"],

I get the error regardless of what field is set as the <DataTextField>. If I
make sure all records have a
UserName not set to NULL the code works great. This can become a big problem
because in many cases
not every field will contain a value. I've thought I woudl just set the
default value of each field
to a blank space, as this will stop the error from happening, but I'm not so
sure I want to do this.

It seems to me this code should work with NULL values. NULL Values frustrate
me at times. Is there a way
I can make the code listed below work with NULL values? FYI: One of my
thoughts was to check for a NULL
value for each field, but this even doesn't sound like a good solution.

Can anyone provide some insight as to how I can make the following code work
when any of the source fields
may contain a NULL value?

Users.aspx (Web Page displaying listbox with UserNames)

<asp:ObjectDataSource
ID="sourceUsers" runat="server"
TypeName="UserComponents.UserDB" SelectMethod="GetUsers">
</asp:ObjectDataSource>
<asp:ListBox
ID="lstUserID" runat="server" DataSourceID="sourceUsers"
DataTextField="UserName" Width="224px">
</asp:ListBox>

UserDetails.cs (in App_Code folder)
namespace UserComponents
{
public class UserDetails
{
public int UserID
{
get { return m_userID; }
set { m_userID = value; }
}
public string UserName
{
get { return m_userName; }
set { m_userName = value; }
}

public UserDetails(int userID, string userName)
{
this.UserID = userID;
this.UserName = userName;
}
public UserDetails()
{
// Default Constructor
}
}
}
UserDB.cs (in App_Code folder)
namespace UserComponents
{
[DataObject]
public class UserDB
{
[DataObjectMethod(DataObjectMethodType.Select, true)]
public List<UserDetails> GetUsers()
{
SqlConnection sqlConn = new SqlConnection(m_strConn);
SqlCommand cmdUsers = new SqlCommand("sUsers", sqlConn);
cmdUsers.CommandType = CommandType.StoredProcedure;
// Create collection of all Users.
List<UserDetails> users = new List<UserDetails>();
try
{
sqlConn.Open();
SqlDataReader rdrUsers = cmdUsers.ExecuteReader();

while (rdrUsers.Read())
{
UserDetails user = new UserDetails( (int)rdrUsers["UserID"],
(string)rdrUsers["UserName"]);
users.Add(user);
}
rdrUsers.Close();
return users;
}
catch (SqlException ex)
{
throw new ApplicationException ("Error Occured");
}
finally
{
sqlConn.Close();
}
}
}
}}
 

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