How to handle NoNullAllowedException in try/catch? - c#

I have a form in C# for inputting some data into a List.
The form consists of text boxes and up and down numeric boxes. Everything works fine but I want to have an error handler (try/catch) in my code so it will check if any of the text boxes are empty or the numeric boxes are left to 0, if thats the case it should pop up an error message.
I tried :
try
{
//code
}
catch (NoNullAllowedException e) //tried it without the e as well
{
//code
}
The code I was having in the brackets its the following one. Sometimes the GetItemDetails() was throwing me an error saying that not all code paths returns a value.
Any thoughts why is doing this or how can I fix it?
public iRepairable GetItemDetails()
{
Shirt shirt = null;
TShirt tshirt = null;
Trouser trouser = null;
Shoe shoe = null;
Boolean isShirt = true;
Boolean isTshirt = true;
Boolean isTrouser = true;
Boolean isShoe = true;
if (rdoShirt.Checked == true)
{
shirt = new Shirt(txtBrand.Text, Convert.ToDouble(txtPrice.Text), Convert.ToInt32(txtAmount.Text), txtCollection.Text);
isTshirt = false;
isTrouser = false;
isShoe = false;
}
else if (rdoTShirt.Checked == true)
{
tshirt = new TShirt(txtBrand.Text, Convert.ToDouble(txtPrice.Text), Convert.ToInt32(txtAmount.Text), txtCollection.Text);
isShirt = false;
isTrouser = false;
isShoe = false;
}
else if (rdoTrouser.Checked == true)
{
trouser = new Trouser(txtBrand.Text, Convert.ToDouble(txtPrice.Text), Convert.ToInt32(txtAmount.Text), txtCollection.Text);
isShirt = false;
isTshirt = false;
isShoe = false;
}
else
{
shoe = new Shoe(txtBrand.Text, Convert.ToDouble(txtPrice.Text), Convert.ToInt32(txtAmount.Text), txtCollection.Text);
isShirt = false;
isTrouser = false;
isTshirt = false;
}
if (isShirt)
{
return shirt;
}
else if (isTshirt)
{
return tshirt;
}
else if (isTrouser)
{
return trouser;
}
else //if(isShoe)
{
return shoe;
}

First of all, the NoNullAllowedException is not for list or just null values. Is the exception that throws when you want to insert null values in a column that doesn't allow them (for more info, MSDN).
For your code, place at the bottom of your code a default return value (but as far as i can see, your code shouldnt break at all)

Related

If Session match string

I got a little problem. I got a if statement which says if Session isn't equal 3, then do something, and if that isn't true, then do something else. My problem is just, that it isn't working proberly.
I've already tried:
1)
if (Session["userrank"] != "3")
{
pnlAdmin.Visible = false;
}
else
{
pnlAdmin.Visible = true;
}
2)
if (Session["userrank"].ToString() != "3")
{
pnlAdmin.Visible = false;
}
else
{
pnlAdmin.Visible = true;
}
3)
if ((string)Session["userrank"] != "3")
{
pnlAdmin.Visible = false;
}
else
{
pnlAdmin.Visible = true;
}
4)
if (((string)Session["userrank"]) != "3")
{
pnlAdmin.Visible = false;
}
else
{
pnlAdmin.Visible = true;
}
but none of them seems to work. And i have already checked if there's a Session called userrank that is getting the result 3.
sorry for the "stupid" question. I'm kind of new to C# & ASP.net.
Best Regards,
Anton
Your code sets pnlAdmin.Visible = false; if whatever is in Session["userrank"] is not 3.
It sets pnlAdmin.Visible = true; if whatever is in Session["userrank"] is 3.
You said it is 3; therefore, the panel should be visible. And that seems to be what is happening.

NullReferenceException was unhandled

I'm just getting the hang of Lightswitch, but I keep getting the null reference exception error when I'm trying to find out if a selected item in a datagrid contains the letters "CMP". I look all over the place but I think I'm doing something wrong. Here is my code for reference:
if(string.IsNullOrWhiteSpace(this.location.SelectedItem.locationID))
{
this.ShowMessageBox("test"); //not sure what to put there so I just made something up
}
else if (this.location.SelectedItem.locationID.Contains("CMP"))
{
this.FindControl("datePurchased").IsVisible = true;
this.FindControl("age").IsVisible = true;
this.FindControl("userList").IsVisible = true;
}
else
{
this.FindControl("datePurchased").IsVisible = false;
this.FindControl("age").IsVisible = false;
this.FindControl("userList").IsVisible = false;
}
I also tried
if(this.location.selecteditem.locationID != null)
if(string.IsNullOrEmpty)
but it always throws me the same error. Any help would be much appreciated!
I guss this.location or this.location.selecteditem may be null, So you got that error.
So please try this if condition instead of your if condition way
if(this.location != null && this.location.selecteditem !=null && this.location.selecteditem.locationID != null)
{
//Write your code here
}
So your final code look like
if(this.location == null && this.location.selecteditem ==null && this.location.selecteditem.locationID == null)
{
this.ShowMessageBox("test"); //not sure what to put there so I just made something up
}
else if (this.location.SelectedItem.locationID.Contains("CMP"))
{
this.FindControl("datePurchased").IsVisible = true;
this.FindControl("age").IsVisible = true;
this.FindControl("userList").IsVisible = true;
}
else
{
this.FindControl("datePurchased").IsVisible = false;
this.FindControl("age").IsVisible = false;
this.FindControl("userList").IsVisible = false;
}

trying to use if, elseif, else loop in checkbox

i am trying to make a program in c#, in which the values of check boxes are retrieved from csv file.I have 4 check boxes and all of them are true or false according to the conditions in csv file. My question is i am using
if (strProg[a] == "JC")
{
chkJogging.Checked = true;
chkCycling.Checked = true;
}
else if(strProg[a] =="C")
{
chkCycling == true
}
else if(strProg[a] == "WK")
{
chkWeightLoss.Checked = true;
chkKoxing.Checked = true
}
else
{
chkBoxing.Checked = false;
chkJogging.Checked = false;
chkCycling.Checked = false;
chkWeightLoss.Checked = false
}
But for some reason the last one 'else' loop is not working. Thanks.
Don't use IF-ELSE This way.
read this : SWITCH-CASE
try this :
switch (strProg[a])
{
case "JC":
chkJogging.Checked = true;
chkCycling.Checked = true;
break;
case "C":
chkCycling.Checked = true;
break;
case "WK":
chkWeightLoss.Checked = true;
chkKoxing.Checked = true;
break;
default:
chkBoxing.Checked = false;
chkJogging.Checked = false;
chkCycling.Checked = false;
chkWeightLoss.Checked = false;
break;
}
you are missing '.Checked' here, so my guess is probably your code is breakin at this point.
else if(strProg[a] =="C")
{
chkCycling == true
}
try to change it with
else if(strProg[a] =="C")
{
chkCycling.Checked == true
}
and see if it works.

Query not updating database

Morning,
I have an issue with some of my code...
Basically i am trying to update or insert into the database. the first if statement if for when adding a new product. the else should then update any existing products.
However when i run it, it is not updating the existing products in the database. It is however setting the items ready to be updated. Any ideas?
Many thanks...
using (aboDataDataContext dc = new aboDataDataContext())
{
foreach (abcProduct p in abcProducts)
{
var match = (from t in dc.abcProducts
where t.sku == p.productcode
select t).FirstOrDefault();
if (match == null)
{
// Watch out here; there is some type conversion required for certain fields!
abcProduct prod = new abcProduct();
prod.sku = p.productcode;
prod.categoryId = dc.Categories.Single(c => c.Name == p.category).Id;
prod.title = p.name;
prod.brand = p.manufacturer;
prod.description = p.description;
prod.abcPrice = p.price;
prod.size = decimal.TryParse(p.size.Replace("cl", ""), out size) == true ? (int?)size : null;
prod.country = p.country;
prod.region = p.region;
prod.vintage = int.TryParse(p.vintage, out vintage) == true ? (int?)vintage : null;
prod.weight = Convert.ToDecimal("1.50");
prod.strength = p.strength;
prod.bottler = p.bottler;
prod.age = int.TryParse(p.age, out age) == true ? (int?)age : null;
prod.caskType = p.casktype;
prod.series = p.series;
prod.flavour = p.flavour;
if (p.freestock <= 0) { prod.stock = 0; } //check to see if stock is 0
else { prod.stock = p.freestock; }
prod.abcUpdated = false;
prod.stockUpdated = false;
prod.priceUpdated = false;
prod.pricePublished = false;
prod.stockPublished = false;
prod.imgPublished = false;
prod.prodPublished = false;
prod.lastUpdated = DateTime.Now;
// Add the new object to the abcProducts table (only in memory here)
dc.abcProducts.InsertOnSubmit(prod);
}
else
{
// update row
match.abcUpdated = true;
//Set if an item has been updated or not.
if (match.stock == p.freestock) { match.stockUpdated = false; }
else { match.stockUpdated = true; }
if (match.abcPrice == p.price) { match.priceUpdated = false; }
else { match.priceUpdated = true;}
match.sku = p.productcode;
match.categoryId = dc.Categories.Single(c => c.Name == p.category).Id;
match.title = p.name;
match.brand = p.manufacturer;
match.description = p.description;
match.stock = p.freestock;
match.abcPrice = p.price;
match.size = decimal.TryParse(p.size.Replace("cl", ""), out size) == true ? (int?)size : null;
match.weight = Convert.ToDecimal("1.50");
match.country = p.country;
match.region = p.region;
match.vintage = int.TryParse(p.vintage, out vintage) == true ? (int?)vintage : null;
match.strength = p.strength;
match.bottler = p.bottler;
match.age = int.TryParse(p.age, out age) == true ? (int?)age : null;
match.caskType = p.casktype;
match.series = p.series;
match.flavour = p.flavour;
if (p.freestock <= 0) { match.stock = 0; } //check to see if stock is 0
else { match.stock = p.freestock; }
match.abcUpdated = true;
match.pricePublished = false;
match.stockPublished = false;
match.imgPublished = false;
match.prodPublished = false;
match.lastUpdated = DateTime.Now;
}
}
// Finally, request Linq to perform the database updates.
dc.SubmitChanges();
}
return null;
}
The context is loosing track of the object when setting match.
At the bottom of the else statement insert
dc.abcProducts.Attach(match);
There is problem in your code, you are iterating through the product table and getting the values in the match variable. In the part of the if statement where match is not null, you are setting the object to the new values, but you are not calling the dc.SubmitChanges();, that object match is not getting stored any where in your code, and in the next iteration in the loop, it is being assigned the new values.
You need to call dc.SubmitChanges(); after update the match values.
foreach (abcProduct p in abcProducts)
{
var match = (from t in dc.abcProducts
where t.sku == p.productcode
select t).FirstOrDefault();
if (match == null)
{
//insertion code commented out
dc.abcProducts.InsertOnSubmit(prod);
}
else
{
///.... setting up all fields.
match.stockPublished = false;
match.imgPublished = false;
match.prodPublished = false;
match.lastUpdated = DateTime.Now;
dc.SubmitChanges(); //Call this otherwise you will
//loose the match values in the next iteration
}
}

How does C# evaluate Logic block?

I have the following line of code:
public bool dcpl_radar()
{
if (radar == null)
return false;
else
{
if (radar != null)
{
if (radar.InvokeRequired)
radar.BeginInvoke(new MethodInvoker(delegate()
{
radar.Visible = false;
}));
else
this.radar.Visible = false;
radar = null;
}
return true;
}//end of else statement
}
but VStudio keeps throwing an error on the invoke line. I've checked the Debugger and if (radar == null) is true, yet VStudio is trying to evaluate a part of the code it shouldn't be in. Can someone explain why it's doing this please?
Wait a minute... I think we have a race condition.
Lets say you BeginInvoke, almost immediately you set radar = null.
There really is no telling when your anonymous delegate will be executed.
I would imagine this should solve your issue.
public bool dcpl_radar()
{
if (radar != null)
{
if (radar.InvokeRequired)
{
radar.BeginInvoke(new MethodInvoker(HideRadar));
}
else
{
HideRadar();
}
return true;
}
return false;
}
private void HideRadar()
{
this.radar.Visible = false;
this.radar = null;
}
What is happening:
The anonymous delegate is being called after you set the radar to null.
How to fix it
public bool dcpl_radar()
{
if (radar == null)
return false;
else
{
if (radar != null)
{
if (radar.InvokeRequired)
radar.BeginInvoke(new MethodInvoker(delegate()
{
radar.Visible = false;
radar = null;
}));
else {
this.radar.Visible = false;
radar = null;
}
}
return true;
}//end of else statement
}
(Note where I've moved your 'null' assignments).
Though I am a bit worried about the point of setting a variable to null, it's generally a sign of a bad design.

Categories