473,322 Members | 1,408 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

Comparison question

I tried to do this:

public static void GetValueFromDbObject(object dbObjectValue, ref decimal
destination)
{
destination = dbObjectValue == DBNull.Value || "" ? decimal.MaxValue :
(decimal)dbObjectValue;
}

Where I am just trying to say if dbObjectValue is either equal to a
DBNull.Value or "", make destination = decimal.MaxValue.

This gives me:

nullHandler.cs(24,18): error CS0019: Operator '||' cannot be applied to
operands of type 'bool' and 'string'

How would I change that statement to do what I am trying to do?

I am trying to move the value passed (dbObjectValue) into destination,
unless = Null or empty string (as this may come from a blank textbox).

Thanks,

Tom
Nov 17 '05 #1
21 2008

tshad wrote:
I tried to do this:

public static void GetValueFromDbObject(object dbObjectValue, ref decimal
destination)
{
destination = dbObjectValue == DBNull.Value || "" ? decimal.MaxValue :
(decimal)dbObjectValue;
}

Where I am just trying to say if dbObjectValue is either equal to a
DBNull.Value or "", make destination = decimal.MaxValue.

This gives me:

nullHandler.cs(24,18): error CS0019: Operator '||' cannot be applied to
operands of type 'bool' and 'string'

How would I change that statement to do what I am trying to do?

I am trying to move the value passed (dbObjectValue) into destination,
unless = Null or empty string (as this may come from a blank textbox).

Thanks,

Tom


The problem is in the order of evaluation. C# is evaluating this part
first:

dbObjectValue == DBNull.Value

This results in a boolean expression, which can't be compared to a
string. To make the ?: operator work you need to compare two like
types. This should work:

destination = ((dbObjectValue == DBNull.Value) ||
(dbObjectValue == string.Empty)) ?
decimal.MaxValue :
(decimal)dbObjectValue;

HTH!
Mike

Nov 17 '05 #2
tshad,

You want to do the following:

public static void GetValueFromDbObject(object dbObjectValue, ref decimal
destination)
{
// If the object is null, or db null, or the object is string, and it is
empty, then
// return the max value.
if (dbObjectValue == null || dbObjectValue == DBNull.Value)
{
// Return the max value.
return decimal.MaxValue;
}

// Check for a string.
string str = object as string;

// If the string is not null, check for empty.
if (str != null)
{
// Trim the string.
str = str.Trim();

// If the string is empty, return the max value.
if (str == string.Empty)
{
// Return the max value.
return decimal.MaxValue;
}

// Set the object to the string.
dbObjectValue = str;
}

// Return the object, converted to a decimal.
return Convert.ToDecimal(dbObjectValue);
}

This checks to see if dbObjectValue is null as well, and it will also
trim the string, if it is a string, which is a little bit different than
what you had, but you might want to check (you can remove it if you have
specific meaning for strings of whitespace and the object is null).

In the end, this could have probably been done in one statement, but
this is a non-trivial piece of logic, and it is more easily maintained like
this.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com
"tshad" <ts**********@ftsolutions.com> wrote in message
news:es**************@TK2MSFTNGP15.phx.gbl...
I tried to do this:

public static void GetValueFromDbObject(object dbObjectValue, ref decimal
destination)
{
destination = dbObjectValue == DBNull.Value || "" ? decimal.MaxValue :
(decimal)dbObjectValue;
}

Where I am just trying to say if dbObjectValue is either equal to a
DBNull.Value or "", make destination = decimal.MaxValue.

This gives me:

nullHandler.cs(24,18): error CS0019: Operator '||' cannot be applied to
operands of type 'bool' and 'string'

How would I change that statement to do what I am trying to do?

I am trying to move the value passed (dbObjectValue) into destination,
unless = Null or empty string (as this may come from a blank textbox).

Thanks,

Tom

Nov 17 '05 #3

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:uN**************@TK2MSFTNGP09.phx.gbl...
tshad,

You want to do the following:

public static void GetValueFromDbObject(object dbObjectValue, ref decimal
destination)
{
// If the object is null, or db null, or the object is string, and it
is empty, then
// return the max value.
if (dbObjectValue == null || dbObjectValue == DBNull.Value)
{
// Return the max value.
return decimal.MaxValue;
}

// Check for a string.
string str = object as string;

// If the string is not null, check for empty.
if (str != null)
{
// Trim the string.
str = str.Trim();

// If the string is empty, return the max value.
if (str == string.Empty)
{
// Return the max value.
return decimal.MaxValue;
}

// Set the object to the string.
dbObjectValue = str;
}

// Return the object, converted to a decimal.
return Convert.ToDecimal(dbObjectValue);
}

This checks to see if dbObjectValue is null as well, and it will also
trim the string, if it is a string, which is a little bit different than
what you had, but you might want to check (you can remove it if you have
specific meaning for strings of whitespace and the object is null).

Why would you check for both null and DBNull.Value?

if (dbObjectValue == null || dbObjectValue == DBNull.Value)

What is happening here is that this would either be a decimal being passed
in either from a decimal variable, textbox or a field from a database.

Thanks,

Tom In the end, this could have probably been done in one statement, but
this is a non-trivial piece of logic, and it is more easily maintained
like this.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com
"tshad" <ts**********@ftsolutions.com> wrote in message
news:es**************@TK2MSFTNGP15.phx.gbl...
I tried to do this:

public static void GetValueFromDbObject(object dbObjectValue, ref
decimal destination)
{
destination = dbObjectValue == DBNull.Value || "" ? decimal.MaxValue :
(decimal)dbObjectValue;
}

Where I am just trying to say if dbObjectValue is either equal to a
DBNull.Value or "", make destination = decimal.MaxValue.

This gives me:

nullHandler.cs(24,18): error CS0019: Operator '||' cannot be applied
to operands of type 'bool' and 'string'

How would I change that statement to do what I am trying to do?

I am trying to move the value passed (dbObjectValue) into destination,
unless = Null or empty string (as this may come from a blank textbox).

Thanks,

Tom


Nov 17 '05 #4

"Mike Hofer" <kc********@gmail.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...

tshad wrote:
I tried to do this:

public static void GetValueFromDbObject(object dbObjectValue, ref
decimal
destination)
{
destination = dbObjectValue == DBNull.Value || "" ? decimal.MaxValue :
(decimal)dbObjectValue;
}

Where I am just trying to say if dbObjectValue is either equal to a
DBNull.Value or "", make destination = decimal.MaxValue.

This gives me:

nullHandler.cs(24,18): error CS0019: Operator '||' cannot be applied
to
operands of type 'bool' and 'string'

How would I change that statement to do what I am trying to do?

I am trying to move the value passed (dbObjectValue) into destination,
unless = Null or empty string (as this may come from a blank textbox).

Thanks,

Tom
The problem is in the order of evaluation. C# is evaluating this part
first:

dbObjectValue == DBNull.Value

This results in a boolean expression, which can't be compared to a
string. To make the ?: operator work you need to compare two like
types. This should work:

destination = ((dbObjectValue == DBNull.Value) ||
(dbObjectValue == string.Empty)) ?
decimal.MaxValue :
(decimal)dbObjectValue;

I tried that and it gives me the following warning:

nullHandler.cs(24,54): warning CS0252: Possible unintended reference
comparison; to get a value comparison, cast the left hand side to type
'string'

Here is the statement

destination = ((dbObjectValue == DBNull.Value) || (dbObjectValue ==
string.Empty)) ? decimal.MaxValue : (decimal)dbObjectValue;

Thanks

Tom
HTH!
Mike

Nov 17 '05 #5
tshad, if your database fields type is decimal (or money etc.) you "cant"
insert an empty string. so you dont have to check for that. and if
dbObjectValue's type can be a string, then (decimal)dbObjectValue will throw
an exception.
Nov 17 '05 #6
"The Crow" <q> wrote in message
news:uQ**************@TK2MSFTNGP10.phx.gbl...
tshad, if your database fields type is decimal (or money etc.) you "cant"
insert an empty string. so you dont have to check for that. and if
dbObjectValue's type can be a string, then (decimal)dbObjectValue will
throw an exception.
I understand that, but I am trying to do something like:

newObject.Salary = theSalary.Text

where theSalary is a textbox.

Normally, you would have a value in the box, but if the textbox was blank,
it will give you an error.

What I want to do is put a Null value into the database, but in my object I
am trying to put the decimal.MaxValue, as you did in your example before.

So if the value is null or empty, I make the decimal the MaxValue.

Thanks,

Tom

Nov 17 '05 #7
Tom,

I don't know what could be passed in. You are passing an object. In
reality, you should have overloads of the method which take specific types,
and call those, not take object. It certainly is possible that a null could
come into this function, depending on things such as data binding (the empty
string could be considered a null value in a textbox) the data adapter (what
if it uses Nullable types in 2.0), etc, etc.

In the end, I don't know what is coming into this object, so I pointed
out some things that you might not have considered.

You really should have type-specific overloads though.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"tshad" <ts**********@ftsolutions.com> wrote in message
news:O1**************@TK2MSFTNGP12.phx.gbl...

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote
in message news:uN**************@TK2MSFTNGP09.phx.gbl...
tshad,

You want to do the following:

public static void GetValueFromDbObject(object dbObjectValue, ref decimal
destination)
{
// If the object is null, or db null, or the object is string, and it
is empty, then
// return the max value.
if (dbObjectValue == null || dbObjectValue == DBNull.Value)
{
// Return the max value.
return decimal.MaxValue;
}

// Check for a string.
string str = object as string;

// If the string is not null, check for empty.
if (str != null)
{
// Trim the string.
str = str.Trim();

// If the string is empty, return the max value.
if (str == string.Empty)
{
// Return the max value.
return decimal.MaxValue;
}

// Set the object to the string.
dbObjectValue = str;
}

// Return the object, converted to a decimal.
return Convert.ToDecimal(dbObjectValue);
}

This checks to see if dbObjectValue is null as well, and it will also
trim the string, if it is a string, which is a little bit different than
what you had, but you might want to check (you can remove it if you have
specific meaning for strings of whitespace and the object is null).


Why would you check for both null and DBNull.Value?

if (dbObjectValue == null || dbObjectValue == DBNull.Value)

What is happening here is that this would either be a decimal being passed
in either from a decimal variable, textbox or a field from a database.

Thanks,

Tom
In the end, this could have probably been done in one statement, but
this is a non-trivial piece of logic, and it is more easily maintained
like this.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com
"tshad" <ts**********@ftsolutions.com> wrote in message
news:es**************@TK2MSFTNGP15.phx.gbl...
I tried to do this:

public static void GetValueFromDbObject(object dbObjectValue, ref
decimal destination)
{
destination = dbObjectValue == DBNull.Value || "" ? decimal.MaxValue :
(decimal)dbObjectValue;
}

Where I am just trying to say if dbObjectValue is either equal to a
DBNull.Value or "", make destination = decimal.MaxValue.

This gives me:

nullHandler.cs(24,18): error CS0019: Operator '||' cannot be applied
to operands of type 'bool' and 'string'

How would I change that statement to do what I am trying to do?

I am trying to move the value passed (dbObjectValue) into destination,
unless = Null or empty string (as this may come from a blank textbox).

Thanks,

Tom



Nov 17 '05 #8
tshad, since you are using my own codes, i think i can say, you have to use
GetValueFromDbObject only when you are getting the value from DataReader or
DataParameter.Value (for output parameters.) :) when getting the decimal
value from textbox, you probably will parse it to decimal
decimal salary = txtSalary.Text == String.Empty ? Decimal.MaxValue :
Decimal.Parse(txtSalary.Text);
and send to business object layer as decimal (as a method parameter or
entity property value.). to give you an idea, i have encapsulated this logic
to an "DecimalPicker" user web control. added javascript for validation and
Value Property. here is my code (my currency uses , as decimal seperator. so
you can modify):

<%@ Control Language="c#" AutoEventWireup="false"
Codebehind="DecimalPicker.ascx.cs"
Inherits="MyCompany.WebUI.WebUserControls.DecimalP icker"
TargetSchema="http://schemas.microsoft.com/intellisense/ie5"%>
<asp:TextBox ID="txtDecimal" Runat="server" CssClass="SaveFormTextBox" />
<asp:RequiredFieldValidator ID="valReqTxtDecimal" Runat="server"
Display="Dynamic" EnableViewState="False" ControlToValidate="txtDecimal">
<img src="/_MyCompanyLayout/images/warnimg.gif" alt="Please enter an valid
value." />
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="valRegExTxtDecimal" Runat="server"
Display="Static" ControlToValidate="txtDecimal" EnableViewState="False"
CssClass="Validator" EnableClientScript="True"
ValidationExpression="^(\d{1,3}(\.\d{3})*|(\d+))(\ ,\d{2})?$">
<img src="/_MyCompanyLayout/images/warnimg.gif" alt="Lütfen Geçerli Bir
E-Mail Giriniz." />
</asp:RegularExpressionValidator>
this is the code behind :
namespace Synapse.WebUI.WebUserControls

{

using System;

using System.Data;

using System.Drawing;

using System.Web;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

using System.Text.RegularExpressions;

public class DecimalPicker : Synapse.WebUI.SynapseWebUserControlBase

{

protected System.Web.UI.WebControls.TextBox txtDecimal;

protected System.Web.UI.WebControls.RegularExpressionValidat or
valRegExTxtDecimal;

protected System.Web.UI.WebControls.RequiredFieldValidator valReqTxtDecimal;

public bool Required

{

get

{

object o = ViewState["Required"];

if(o == null)

return true;

else

return (bool)o;

}

set

{

ViewState["Required"] = value;

}

}

public bool Enabled

{

get{return txtDecimal.Enabled;}

set{txtDecimal.Enabled = value;}

}

public decimal Value

{

get

{

return txtDecimal.Text == String.Empty ? Decimal.MaxValue :
Decimal.Parse(txtDecimal.Text);

}

set

{

txtDecimal.Text = value == Decimal.MaxValue ? String.Empty :
value.ToString();

}

}

#region Web Form Designer generated code

override protected void OnInit(EventArgs e)

{

InitializeComponent();

base.OnInit(e);

}
private void InitializeComponent()

{

}

#endregion

protected override void OnPreRender(EventArgs e)

{

valReqTxtDecimal.Enabled = Required;

base.OnPreRender (e);

}

}

}
Nov 17 '05 #9
you cannot assign to Salary porperty of newObject a string. (at least you
shouldnt.)
Nov 17 '05 #10
Nicholas, IDataReader's indexer return object and IDbParameter.Value
property is an object. so i dont think you can use overloading. (method is
designed to take the value of database value's and convert it to a specific
type and contains some little logic doing this.)
Nov 17 '05 #11
the warning means, you cannot compare an object to a string using ==
operator. normally == operator compares object references. but string's
overload's this operator and gives different meaning. fallowing would be
right way doing that.

destination = ((dbObjectValue == DBNull.Value) ||
(dbObjectValue.ToString() ==
string.Empty)) ? decimal.MaxValue : (decimal)dbObjectValue;

you may wonder, why dbObjectValue == DBNull.Value worked? its just because
DBNull.Value designed as singleton pattern. this means that "the system has
only one instance of DBNull"
So == operator worked as expected.
Nov 17 '05 #12
"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:Oa**************@TK2MSFTNGP09.phx.gbl...
Tom,

I don't know what could be passed in. You are passing an object. In
reality, you should have overloads of the method which take specific
types, and call those, not take object. It certainly is possible that a
null could come into this function, depending on things such as data
binding (the empty string could be considered a null value in a textbox)
the data adapter (what if it uses Nullable types in 2.0), etc, etc.

In the end, I don't know what is coming into this object, so I pointed
out some things that you might not have considered.

You really should have type-specific overloads though.
I agree and I do.

This was just an example.

But the problem is really a textbox. If you do:

myObject.Salary = Salary.Text

I am looking for a decimal value. But Salary.Text could also be empty.
This would give me an error as an empty string is not a decimal.

Typically, I would check this first and pass a 0 or maybe a -1 if it is
empty, but I am trying to do this inside my object.

I would have the same problem with the overloads for int or dates as well.

Tom


--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"tshad" <ts**********@ftsolutions.com> wrote in message
news:O1**************@TK2MSFTNGP12.phx.gbl...

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote
in message news:uN**************@TK2MSFTNGP09.phx.gbl...
tshad,

You want to do the following:

public static void GetValueFromDbObject(object dbObjectValue, ref
decimal destination)
{
// If the object is null, or db null, or the object is string, and it
is empty, then
// return the max value.
if (dbObjectValue == null || dbObjectValue == DBNull.Value)
{
// Return the max value.
return decimal.MaxValue;
}

// Check for a string.
string str = object as string;

// If the string is not null, check for empty.
if (str != null)
{
// Trim the string.
str = str.Trim();

// If the string is empty, return the max value.
if (str == string.Empty)
{
// Return the max value.
return decimal.MaxValue;
}

// Set the object to the string.
dbObjectValue = str;
}

// Return the object, converted to a decimal.
return Convert.ToDecimal(dbObjectValue);
}

This checks to see if dbObjectValue is null as well, and it will also
trim the string, if it is a string, which is a little bit different than
what you had, but you might want to check (you can remove it if you have
specific meaning for strings of whitespace and the object is null).


Why would you check for both null and DBNull.Value?

if (dbObjectValue == null || dbObjectValue == DBNull.Value)

What is happening here is that this would either be a decimal being
passed in either from a decimal variable, textbox or a field from a
database.

Thanks,

Tom
In the end, this could have probably been done in one statement, but
this is a non-trivial piece of logic, and it is more easily maintained
like this.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com
"tshad" <ts**********@ftsolutions.com> wrote in message
news:es**************@TK2MSFTNGP15.phx.gbl...
I tried to do this:

public static void GetValueFromDbObject(object dbObjectValue, ref
decimal destination)
{
destination = dbObjectValue == DBNull.Value || "" ? decimal.MaxValue
: (decimal)dbObjectValue;
}

Where I am just trying to say if dbObjectValue is either equal to a
DBNull.Value or "", make destination = decimal.MaxValue.

This gives me:

nullHandler.cs(24,18): error CS0019: Operator '||' cannot be applied
to operands of type 'bool' and 'string'

How would I change that statement to do what I am trying to do?

I am trying to move the value passed (dbObjectValue) into destination,
unless = Null or empty string (as this may come from a blank textbox).

Thanks,

Tom



Nov 17 '05 #13

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:uN**************@TK2MSFTNGP09.phx.gbl...
tshad,

You want to do the following:

I tried your code, but got an error on:

// Check for a string.
string str = object as string;

The error was:

nullHandler.cs(34,24): error CS1525: Invalid expression term 'object'
nullHandler.cs(34,27): error CS1002: ; expected
nullHandler.cs(34,33): error CS1001: Identifier expected

Do you know what caused that?

Thanks,

Tom
public static void GetValueFromDbObject(object dbObjectValue, ref decimal
destination)
{
// If the object is null, or db null, or the object is string, and it
is empty, then
// return the max value.
if (dbObjectValue == null || dbObjectValue == DBNull.Value)
{
// Return the max value.
return decimal.MaxValue;
}

// Check for a string.
string str = object as string;

// If the string is not null, check for empty.
if (str != null)
{
// Trim the string.
str = str.Trim();

// If the string is empty, return the max value.
if (str == string.Empty)
{
// Return the max value.
return decimal.MaxValue;
}

// Set the object to the string.
dbObjectValue = str;
}

// Return the object, converted to a decimal.
return Convert.ToDecimal(dbObjectValue);
}

This checks to see if dbObjectValue is null as well, and it will also
trim the string, if it is a string, which is a little bit different than
what you had, but you might want to check (you can remove it if you have
specific meaning for strings of whitespace and the object is null).

In the end, this could have probably been done in one statement, but
this is a non-trivial piece of logic, and it is more easily maintained
like this.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com
"tshad" <ts**********@ftsolutions.com> wrote in message
news:es**************@TK2MSFTNGP15.phx.gbl...
I tried to do this:

public static void GetValueFromDbObject(object dbObjectValue, ref
decimal destination)
{
destination = dbObjectValue == DBNull.Value || "" ? decimal.MaxValue :
(decimal)dbObjectValue;
}

Where I am just trying to say if dbObjectValue is either equal to a
DBNull.Value or "", make destination = decimal.MaxValue.

This gives me:

nullHandler.cs(24,18): error CS0019: Operator '||' cannot be applied
to operands of type 'bool' and 'string'

How would I change that statement to do what I am trying to do?

I am trying to move the value passed (dbObjectValue) into destination,
unless = Null or empty string (as this may come from a blank textbox).

Thanks,

Tom


Nov 17 '05 #14

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:uN**************@TK2MSFTNGP09.phx.gbl...
tshad,

You want to do the following:

public static void GetValueFromDbObject(object dbObjectValue, ref decimal
destination)
{
// If the object is null, or db null, or the object is string, and it is empty, then
// return the max value.
if (dbObjectValue == null || dbObjectValue == DBNull.Value)
{
// Return the max value.
return decimal.MaxValue;
}

// Check for a string.
string str = object as string;
This works really well if I change the above to: string str =
(string)dbObjectValue;

But it only works if I am using a textbox, such as:

myObject.Salary = salary.Text

but if I do:

myObject.Salary = 100;

or

decimal temp = 100;
myObject.Salary = temp;

I get an error at the line: string str = (string)dbObjectValue;

It gives me the error:

Specified Cast is not Valid.

I assume this is because I am passing an actual decimal and not a string to
be converted to decimal.

Is there a way to test to see if the object is string (text) or decimal
before trying to test it?

Thanks,

Tom
// If the string is not null, check for empty.
if (str != null)
{
// Trim the string.
str = str.Trim();

// If the string is empty, return the max value.
if (str == string.Empty)
{
// Return the max value.
return decimal.MaxValue;
}

// Set the object to the string.
dbObjectValue = str;
}

// Return the object, converted to a decimal.
return Convert.ToDecimal(dbObjectValue);
}

This checks to see if dbObjectValue is null as well, and it will also
trim the string, if it is a string, which is a little bit different than
what you had, but you might want to check (you can remove it if you have
specific meaning for strings of whitespace and the object is null).

In the end, this could have probably been done in one statement, but
this is a non-trivial piece of logic, and it is more easily maintained like this.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com
"tshad" <ts**********@ftsolutions.com> wrote in message
news:es**************@TK2MSFTNGP15.phx.gbl...
I tried to do this:

public static void GetValueFromDbObject(object dbObjectValue, ref decimal destination)
{
destination = dbObjectValue == DBNull.Value || "" ? decimal.MaxValue :
(decimal)dbObjectValue;
}

Where I am just trying to say if dbObjectValue is either equal to a
DBNull.Value or "", make destination = decimal.MaxValue.

This gives me:

nullHandler.cs(24,18): error CS0019: Operator '||' cannot be applied to operands of type 'bool' and 'string'

How would I change that statement to do what I am trying to do?

I am trying to move the value passed (dbObjectValue) into destination,
unless = Null or empty string (as this may come from a blank textbox).

Thanks,

Tom


Nov 17 '05 #15
tshad <tf*@dslextreme.com> wrote:
// Check for a string.
string str = object as string;


This works really well if I change the above to: string str =
(string)dbObjectValue;


<snip>

As you've seen, that fails if dbObjectValue is a string. If you change
Nick's example slightly less though, to:

string str = dbObjectValue as string;

then it will work, because his next line was:

if (str != null)

The "as" operator is like casting, but the result is null if the type
isn't the one you're trying to use it as. (Casting also potentially
performs extra conversions which as doesn't, but that's not relevant
here.)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #16
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP***********************@msnews.microsoft.co m...
tshad <tf*@dslextreme.com> wrote:
// Check for a string.
string str = object as string;
This works really well if I change the above to: string str =
(string)dbObjectValue;


<snip>

As you've seen, that fails if dbObjectValue is a string. If you change
Nick's example slightly less though, to:

string str = dbObjectValue as string;

then it will work, because his next line was:

if (str != null)

The "as" operator is like casting, but the result is null if the type
isn't the one you're trying to use it as. (Casting also potentially
performs extra conversions which as doesn't, but that's not relevant
here.)


You're right (as was Nick). It works great.

I was confused on the "as". I thought maybe he made a mistake and was
thinking VB.Net. Also, he used object instead of dbObjectValue I wasn't
sure if that was a mistake or I didn't understand what he was doing.

So now I can handle the Set, but still have a problem with the get, which is
going to be a little more difficult to deal with.

It almost works. As a matter of fact it works for all the situations I have
tested for except if the TextBox was blank. The problem is when I did a Set
and changed the value to decimal.MaxValue (in the decimal case). I have no
way to know if the value was set because the original value was DBNull.Value
or blank. Both cases I set to MaxValue. With the Get I don't know what to
set the value to. If I set it to a DBNull.Value and it is a TextBox, I get
an error.

Here is the code to return the Null if the value was set to MaxValue.

public static object SetDbObjectValueFromValue(decimal sourceValue, ref
object dbObjectValue)
{
if(sourceValue == decimal.MaxValue)
dbObjectValue = DBNull.Value;
else
dbObjectValue = sourceValue;
return dbObjectValue;
}

The Get/Set code is:

public object Salary
{
get
{
object value = null;
return NullHandler.SetDbObjectValueFromValue(salary,ref value);
}
set
{
NullHandler.GetValueFromDbObject(value,ref salary);
}
}

The code to get the value for a TextBox is:

salary.Text = newTestNulls.Salary

This will get me the error: "Cast from type 'DBNull' to type 'String' is
not valid."

The only way I can see to solve the problem would be to set the Class
variable to MaxValue if DBNull and MaxValue-1 if blank.

Thanks,

Tom --
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Nov 17 '05 #17
if you use object type for Salary, why dont you use DBNull.Value if value is
DBNull and use Decimal.MaxValue ? i think you are very very confused.
Nov 17 '05 #18
"The Crow" <q> wrote in message
news:uI**************@TK2MSFTNGP15.phx.gbl...
if you use object type for Salary, why dont you use DBNull.Value if value is DBNull and use Decimal.MaxValue ? i think you are very very confused.


Probably true.

I am not sure what you are saying here.

Salary (object) is my property to allow me to access salary (decimal).

Can you set the value of Salary?

I thought properties were only a way to access my private variables, but not
really a variable itself. I could be wrong here.

To access salary, I would do myObject.Salary - where Salary is just function
to get and set salary (I thought.

Tom
Nov 17 '05 #19
you sure right about what properties are. but you should use (in my opinion)
decimal as data type of your property. if you will use object as datatype,
then dont bother with DBNull. just assign dbnull directly. my intention
using Decimal.MaxValue was because decimal type cant hold null values...

you shouldnt assign a string to salary as database persistence will be a
disaster because your column type is decimal (or probably money in sql
server.).

have you inspected my decimalpicker example?
Nov 17 '05 #20
"The Crow" <q> wrote in message
news:e1**************@TK2MSFTNGP10.phx.gbl...
you sure right about what properties are. but you should use (in my
opinion) decimal as data type of your property. if you will use object as
datatype, then dont bother with DBNull. just assign dbnull directly. my
intention using Decimal.MaxValue was because decimal type cant hold null
values...
But if I do that I won't be able to use the property directly
(myObject.Salary = mySalary.Text). Because mySalary.Text happens to be
blank, I end up with an error (as you can't assign a blank text field to a
decimal field).

you shouldnt assign a string to salary as database persistence will be a
disaster because your column type is decimal (or probably money in sql
server.).
I am not assigning a string to salary but converting the string to decimal
in the property methods.

have you inspected my decimalpicker example?


Yes, I assume you are talking about your nullHandler example..

That was where I got the idea of doing my class.

In your nullHandler, you pass an Object to the GetValueFromDbObject methods.
I call this from my Set/method and the overload is controlled by the
datatype of the private variable (salary).

Your handler works fine as long as you are not passing an empty textbox,
which was why I had to modify it. I wanted to handle the data regardless of
whether a textbox was being passed, decimal variable or decimal constant. I
also wanted to be able let the class handle conversions.

I didn't want to have to remember to use .ToString or .ToDecimal in my
code - I wanted the class to handle that.

My problem is that I needed to use 2 values MaxValue and MaxValue-1 to
handle the DBNull value as well as the Empty string value. If it came in as
an Empty string I would use that in my Get also (as a DBNull would cause an
error, if I was returning that to a textbox).

This may not work as cleanly as I would like as I cannot get the Get to work
correctly. This is because I have no way of knowing whether I am returning
the value to a Textbox or a decimal variable. I can't return an empty
string to a variable and I can't return a DBNull.Value to a textbox).

Tom
Nov 17 '05 #21
i suggested you using custom web user control that returns you decimal value
instead of string. but if you really want to this approach use something
like :
public object Salary
{
get{return salary;}
set
{
if(value == null || value == DBNull.Value) //again we take advantage
of DBNull.Value returns same instance in scope of the application
salary = DBNull.Value;
else if(typeof(value) == typeof(string)
{
if(value.ToString() == String.Empty)
salary = DBNull.Value;
else
salary = Decimal.Parse(value.ToString()); // you can use try
catch block here and throw your own exception rather then CLR's to be thrown
when string is not a correct string...
}
else if(typeof(value) == typeof(decimal)
salary = value;
else
throw new ApplicationException("Salary must be assigned to
either decimal or string value");
}
}
i think this approach suffers from performance a bit and user of the class
have to know that he/she can assign only decimal and string values to the
property. but it also leaves far less job to UI (parsing and checking for
null or DbNull or empty strings.). if you will use this approach and dont
want write this code everytime you can encapsulate that code in a static
method in your project and use everywhere.

public sealed class ValueSetterHelper // we use sealed to gain performance
and prevent inheriting from this class.
{
private ValueSetterHelper() // we use private constructor to prevent
instaninating this class.
{
}

public static object HandleDecimalValue(object value)
{
if(value == null || value == DBNull.Value) //again we take advantage
of DBNull.Value returns same instance in scope of the application
return DBNull.Value;
else if(typeof(value) == typeof(string)
{
if(value.ToString() == String.Empty)
return DBNull.Value;
else
return Decimal.Parse(value.ToString()); // you can use try
catch block here and throw your own exception rather then CLR's to be thrown
when string is not a correct string...
}
else if(typeof(value) == typeof(decimal)
return value;
else
throw new ApplicationException("Salary must be assigned to
either decimal or string value");
}
}

public object Salary
{
get{return salary;}
set{salary = ValueSetterHelper.HandleDecimalValue(value);
}
and i want to ask readers of this post, how is this approach?
Nov 17 '05 #22

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

29
by: Steven D'Aprano | last post by:
Playing around with comparisons of functions (don't ask), I discovered an interesting bit of unintuitive behaviour: >>> (lambda y: y) < (lambda y: y) False Do the comparison again and things...
46
by: yadurajj | last post by:
Hello i am newbie trying to learn C..I need to know about string comparisons in C, without using a library function,...recently I was asked this in an interview..I can write a small program but I...
5
by: BILL | last post by:
Hi Everyone, I've been looking through these .NET groups and can't find the exact answer I want, so I'm asking. Can someone let me know the best way (you feel) to search a C# string for an...
37
by: spam.noam | last post by:
Hello, Guido has decided, in python-dev, that in Py3K the id-based order comparisons will be dropped. This means that, for example, "{} < " will raise a TypeError instead of the current...
2
by: eastern_strider | last post by:
I'm running into problems about defining a comparison function for a map which has a user defined key. For example: class Key { public: string name; int number; Key (na, nu) : name (na),...
0
by: SvenMathijssen | last post by:
Hi, I've been wrestling with a problem for some time that ought to be fairly simple, but turns out to be very difficult for me to solve. Maybe someone here knows the answer. What I try to do is...
3
by: =?Utf-8?B?R0I=?= | last post by:
I have created a small program that illustrates the problem. I would know how to address the fields that I want to sort on in the greaterThan comparison. Anybody who knows?? using System; ...
37
by: Michele Simionato | last post by:
At work we are shopping for a Web framework, so I have been looking at the available options on the current market. In particular I have looked at Paste and Pylons and I have written my...
5
by: evanevankan2 | last post by:
I have a question about the warning 'comparison between signed and unsigned' I get from my code. It comes from the conditional in the outer for loop. I understand the warning, but I'm not sure...
2
by: puzzlecracker | last post by:
Unlike C++, in Csharp you're only allowed to compare a generic type T with null, if the method it's passed in not implementing IComparable<Tor , IEquatable<T(still don't know why we need these...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.