Handle Null condition - asp.net

I want to handle null condition in below code.
lstTest.Discount = If((Not dataSet.Tables("History") Is Nothing),
If(IsDBNull(dataSet.Tables("History").Rows(0)("DiscountsAdjustmentsAmount")),
"$0.00",
StringToCurrency(GetContractualDiscount(dataSet.Tables("History").Rows(0)
("DiscountsAdjustmentsAmount"), dataSet.Tables("History").Rows(0)
("DiscountsAdjustments"), dataSet.Tables("History").Rows(0)
("EstimatedCharges")))), "$0.00")
My code is getting break at
dataSet.Tables("History").Rows(0)("DiscountsAdjustments")
since its value is null. I want to replace null value with "0.00"
Please help how can I handle.
Thanks

Rahul,
You will likely need to rewrite this part of it. Here is your original code:
lstTest.Discount = If((Not dataSet.Tables("History") Is Nothing),
If(IsDBNull(dataSet.Tables("History").Rows(0)("DiscountsAdjustmentsAmount")),
"$0.00",
StringToCurrency(GetContractualDiscount(dataSet.Tables("History").Rows(0)
("DiscountsAdjustmentsAmount"), dataSet.Tables("History").Rows(0)
("DiscountsAdjustments"), dataSet.Tables("History").Rows(0)
("EstimatedCharges")))), "$0.00")
Instead of this big nested mess... why not do it this way. Note I dont have a VB debugger in front of me so there may be some slight format adjustments, so consider this pseudo code:
Is the dataset valid
If Not IsDBNull(dataSet.Tables("History"))
''We know that we have data in our dataset
''Do all your checks
if Not isDBNull(dataSet.Tables("History").Rows(0)("Your field"))
''Do something
Else
''Show a 0
END IF
''REPEAT THE ABOVE LINES FOR EACH FIELD
End if

You can check for null on any column first using methods on the DataRow object:
Which of IsDBNull and IsNull should be used?

Related

How to remove duplicates in a listbox VB.net

I am trying to remove duplicates in a ListBox which is populated by a query pull. I use this code to prevent adding duplicates in VB 6.0 but does not work when converted over to VB.net. Is there a substitute method to prevent or remove duplicates.
colSchema = dr("Col_Schema").ToString
If Not lstSchema.Items.ToString.Contains(colSchema) Then
lstSchema.Items.Add(New ListItem(colSchema))
End If
try
colSchema = dr("Col_Schema").ToString
dim exists as boolean = false
for i as integer = 0 to lstSchema.items.count - 1
if lstSchema.items.item(i) = colSchema then
exists = true
end if
next
if exists = false then
lstSchema.Items.Add(New ListItem(colSchema))
end if
This code
lstSchema.Items.ToString
is converting Items to a string. Items is most likely the type ListBox.ObjectCollection (if this is WinForms) or a similar collection type for other UI frameworks. Calling ToString on such classes will end up calling Object.ToString, which just returns the name of the class.
Instead, try
lstSchema.Items.Contains(colSchema)
If that does not work for some reason, please update your question explaining exactly what you were trying to solve by calling ToString.

How to use AND in a CASE sqlite statement for validation check?

I'v a SQLite database and I want to generate a kind of validation check.
The main target is to compare three fields in a table. If stnd_sht has the value 'nicht gegeben' then there should be a entry either in mass_sof of in mass_6m, if not then plausibility is not given.
So far I tried the following:
SELECT
b.baum_id AS baum_id,
CASE
WHEN b.stnd_sht ='nicht gegeben' AND b.mass_sof IS NULL THEN 'fehler'
WHEN b.stnd_sht ='nicht gegeben' AND b.mass_6m IS NULL THEN 'fehler'
ELSE 'plausibel' END AS plaus
FROM baeume b;
and...
SELECT
b.baum_id AS baum_id,
CASE WHEN (b.mass_sof IS NULL OR b.mass_6m IS NULL) AND b.stnd_sht ='nicht gegeben' THEN 'fehler'
ELSE 'plausibel' END AS plaus
FROM baeume b;
Everything works fine without any AND or OR operator but as I add additional expressions the result is not correct.
Is the AND operator not supportet by the CASE statement, or am I totaly wrong and the statement needs another structure or has to be more complex?
Thanks in advance, Patrick
These expressions are syntactically correct, but do not correspond to the explanation.
Sometimes, it helps to reverse a logical condition.
According to the explanation, there is an error if stnd_sht is nicht gegeben and if both the mass_sof and mass_6m values are NULL.
This would correspond to the following expression:
SELECT baum_id,
CASE WHEN stnd_sht = 'nicht gegeben' AND
mass_sof IS NULL AND
mass_6m IS NULL
THEN 'fehler'
ELSE 'plausibel'
END AS plaus
FROM baeume;
This could be simplified a little:
SELECT baum_id,
CASE WHEN stnd_sht = 'nicht gegeben' AND
COALESCE(mass_sof, mass_6m) IS NULL
THEN 'fehler'
ELSE 'plausibel'
END AS plaus
FROM baeume;

Dealing with Nulls from a DataReader

I have done this in the past, but I cant remember the correct way to deal with DBNULLS.
This is vb.net
The error im getting is Conversion from type 'DBNull' to type 'Integer' is not valid.
Here is the code.
Dim reader As MySqlDataReader = command.ExecuteReader
Do While reader.Read
Dim item As New clsProvider(reader.Item("MasterAccountID"), reader.Item("CompanyName"), reader.Item("Address"), reader.Item("Postcode"), reader.Item("Telephone"), reader.Item("Fax"), reader.Item("Number_of_Companies"), reader.Item("Total_Number_of_employees"), reader.Item("MainContactName"), reader.Item("MainContactPhone"), reader.Item("MainContactEmail"), reader.Item("Fee"), Convert.ToString(reader.Item("Notes")))
list.Add(item)
Loop
reader.Close()
The issue i have is that some of the items may be empty in the DB. I'm sure in the past I have done something like
convert.ToString(reader.item("Something")
But for the life of me i cant remember.
If the column is nullable, then you should check for null:
If (reader.IsDBNull(ordinal))
See IsDBNull
Perhaps
reader.item("Something").ToString()
is what you've done before?
This isn't necessarily correct but it does deal with null strings quite effectively.
Perhaps:
IFF(reader.item("Something") != DBNull.Value, reader.item("Something"), "")
You have to first check if the column value is null (check the incoming value for DBNull). Once you know that you can decide what to do next - assign null or some other default value to your variable.
I am not sure if my VB.Net is still upto the mark but something like this should help:
Dim item As New clsProvider
item.AccountId = TryCast(reader.Item("MasterAccountID"), String)
item.SomeInt= If(TryCast(reader.Item("SomeInt"), System.Nullable(Of Integer)), 0)
Use TryCast to check if cast is possible.

SelectedValue which is invalid because it does not exist in the list of items

I encounter this problem repeatedly, and haven't a clue what is causing it. I get an exception in the DataBind: SelectedValue which is invalid because it does not exist in the list of items.
Here are some important pieces of information:
I reload listOrgs periodically when the underlying data has changed.
The Organization.DTListAll call returns 2 Int, String pairs.
There are no duplicate or null values in the returned data
After the first two lines below, listOrgs.Items.Count is 0, and the Selected Value is 0
The selected value after the DataBind operation executes is the ID value from the first row in the data
This exception happens the very first time this code is executed after a fresh page load
listOrgs.Items.Clear();
listOrgs.SelectedValue = "0";
listOrgs.DataSource = new Organization().DTListAll(SiteID);
listOrgs.DataTextField = "OrganizationName";
listOrgs.DataValueField = "OrganizationID";
listOrgs.DataBind();
Apparently the solution I posted wasn't entirely effective... Eventually in my application I changed to this:
listOrgs.Items.Clear();
listOrgs.SelectedIndex = -1;
listOrgs.SelectedValue = null;
listOrgs.ClearSelection(); // Clears the selection to avoid the exception (only one of these should be enough but in my application I needed all..)
listOrgs.DataSource = new Organization().DTListAll(SiteID);
listOrgs.DataTextField = "OrganizationName";
listOrgs.DataValueField = "OrganizationID";
listOrgs.DataBind();
I kept getting this error.
Weird thing is that before I set the datasource and rebind after deleting an item the selected index = -1.
If I explicitly set the selectedIndex = -1; then it works and doesn't throw an error.
So even though it was already -1 setting it to -1 stops it from erroring.
Weird eh?
Try setting listOrgs.SelectedValue = "0" after you refresh the DataSource
At the moment you are trying to select the first item in an empty list.
Change the first two line with this :
listOrgs.SelectedItem.Selected = false;
listOrgs.Items.Clear();
In case you still have this problem this is how i resolved it:
listOrgs.SelectedIndex = -1; // Clears the SelectedIndex to avoid the exception
listOrgs.DataSource = new Organization().DTListAll(SiteID);
listOrgs.DataTextField = "OrganizationName";
listOrgs.DataValueField = "OrganizationID";
listOrgs.DataBind(); //Unless you have "listOrgs.AppendDataBoundItems = true" you don't need to clear the list
#PMarques answer helped me out and did solve my problem.
However whilst experimenting, it clicked in my head why I was gettign the error in the first place.
I was setting the "Text" attribute thinking that it might create an encompassing label or fieldset + legend, for me (which it doesn't).
The Text property for a list is infact the SelectedValue property for a ListControl.
So my mistake in misinterpreting what the text property did.
Not sure it is your case, but I had the same problem and apparently there was no explanation, then I realized doing a copy and paste on notepad of a field of database that at the beginning of the value there was a NULL.
Curious thing was that a select joining tables was working. I deleted the row and reinserted, after was working fine.
I was getting the same error repeatedly and try ending up by not setting the default selected value to Index -1.
I commented my code ddlDRIBidAmt.SelectedValue = -1
This value was set at the time where my Page Controls were reset to default values.
I know its too late to answer, but what I tried is an dirty solution but it worked.
After databinding, I am insert a item at index 0
ddl.Items.Insert(0, new ListItem("---Select---","-1"));
And on setting,
I am placing try catch, In catch i am setting Value to -1

How can I tell if E4X expression has a match or not?

I am trying to access an XMLList item and convert it to am XML object.
I am using this expression:
masonicXML.item.(#style_number == styleNum)
For example if there is a match everything works fine but if there is not a match then I get an error when I try cast it as XML saying that it has to be well formed. So I need to make sure that the expression gets a match before I cast it as XML. I tried setting it to an XMLList variable and checking if it as a text() propertie like this:
var defaultItem:XMLList = DataModel.instance.masonicXML.item.(#style_number == styleNum);
if(defaultItem.text())
{
DataModel.instance.selectedItem = XML(defaultItem);
}
But it still give me an error if theres no match. It works fine if there is a match.
THANKS!
In my experience, the simplest way to check for results is to grab the 0th element of the list and see if it's null.
Here is your code sample with a few tweaks. Notice that I've changed the type of defaultItem from XMLList to XML, and I'm assigning it to the 0th element of the list.
var defaultItem:XML =
DataModel.instance.masonicXML.item.(#style_number == styleNum)[0];
if( defaultItem != null )
{
DataModel.instance.selectedItem = defaultItem;
}
OK I got it to work with this:
if(String(defaultItem.#style_number).length)
Matt's null check is a good solution. (Unless there is the possibility of having null items within an XMLList.. probably not, but I haven't verified this.)
You can also check for the length of the XMLList without casting it to a String:
if (defaultItem.#style_number.length() > 0)
The difference to String and Array is that with an XMLList, length() is a method instead of a property.

Resources