-2

I have the below code:

var ConLeads = repo.Find(Int32.Parse(Request.QueryString["id"]));

***var Customer = Custrepo.Find(Int32.Parse(ConLeads.ClientName));***

IDTextBox.Text = ConLeads.ID;
CreatedByTextBox.Text = ConLeads.CreatedBy;
***ExisitingClientTextBox.Text = Customer.Client_Name;***
NewClientTextBox.Text = ConLeads.PotentialClientName;
ContactNameTextBox.Text = ConLeads.ContactName;
IssueDateTextBox.Text = ConLeads.IssueDate;
DetailsTextBox.Text = ConLeads.Details;
ClientTelNoTextBox.Text = ConLeads.ClientTelNo;
ClientIDTextBox.Text = ConLeads.ClientName;

I receive the below error message when running my code on the lines above in Bold and Italic:

Input string was not in a correct format Error

The reason the error occurs is due to the cell in the database being blank. This is correct as not all entries will have a value as the ExisitingClientTextBox is not a mandatory filed that required an entry into the database. Is there a way to stop this error occurring when the Database value is blank?

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
  • 2
    I wouldnt expect a clientname to be an integer.. – BugFinder Feb 06 '18 at 11:09
  • 2
    If you use the [debugger](https://msdn.microsoft.com/en-US/library/dn986851.aspx) and inspect the value of `ConLeads.ClientName`, what does it tell you? – rene Feb 06 '18 at 11:10
  • also relevant: https://stackoverflow.com/questions/1019793/how-can-i-convert-string-to-int/1019804#1019804 – rene Feb 06 '18 at 11:12
  • Not all elements have an `Id`? Sounds weird, but okay. But how do you plan to *find* the element if not by some property? What do you want to do if the value *is* blank? – MakePeaceGreatAgain Feb 06 '18 at 11:13
  • 1
    am I missing something or you just need to use `if(!string.isNullOrEmpty(ConLeads.ClientName)){ those two lines marked wth ***}` – Mike Makarov Feb 06 '18 at 11:14
  • Thank for Mike Makarov, that has worked for me. Apologies if my query was rather vague. – JonnyGareth30 Feb 08 '18 at 14:43

2 Answers2

0

This is a specific behavior of parse. It is know to throw "Vexing Exceptions": Exceptions you have to handle and can not avoid without implementing the whole thing yoruself. As taht was too annoying, the Framework team added TryParse() pretty much with Framework 2.0.

See also: http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx

Aside from filtering out the "blank" case, TryParse would be the obvious solution.

However as others pointed out, your database design might be broken. For starters, why is a number stored or transmited as string that you need to parse? And some Rows do not have a primary key (ID) apparently?

Christopher
  • 9,634
  • 2
  • 17
  • 31
0

You can try :

int result;
if(int.TryParse(Request.QueryString["id"], out result))
                {
                   var ConLeads = repo.Find(result);

                }
rahulaga-msft
  • 3,964
  • 6
  • 26
  • 44