0

When i give empty value to bank region and cost centre it gives the error during saving to database.

Error:input string was not in a correct format.

   objMEndorsement.BankRegion =  Convert.ToInt32(txtBankRegion.Text);
   objMEndorsement.CostCenter = Convert.ToInt32(txtCostCenter.Text); 

this is the code i used.How i will save empty textbox value to database.

4
  • 1
    Empty value cannot be converted into int. Commented Aug 19, 2015 at 10:44
  • 2
    You could store as a nullable int int? Commented Aug 19, 2015 at 10:44
  • Then how i have to do. Commented Aug 19, 2015 at 10:44
  • 1
    Check for empty or null values before trying to convert to int. like this - string.IsNullOrWhiteSpace(txtBankRegion.Text) Commented Aug 19, 2015 at 10:49

6 Answers 6

2

Try something like this:

objMEndorsement.BankRegion =  string.IsNullOrWhiteSpace(txtBankRegion.Text) ? 0 : Convert.ToInt32(txtBankRegion.Text)
Sign up to request clarification or add additional context in comments.

Comments

0

Replace

 objMEndorsement.BankRegion =  Convert.ToInt32(txtBankRegion.Text);
 objMEndorsement.CostCenter = Convert.ToInt32(txtCostCenter.Text);

by

 objMEndorsement.BankRegion =  Convert.ToInt32(txtBankRegion.Text??0);
 objMEndorsement.CostCenter = Convert.ToInt32(txtCostCenter.Text??0); 

?? is null coalesce operator in c#

EDIT: Best option would be to use tryParse like this

bool isInteger=int.TryParse(txtBankRegion.Text??0, out num1);
if(isInteger)
{
//insert into database
}

Comments

0

Try to use int.TryParse() this is better in handling conversion.

You can do it this way:

int bankRegion = 0; //Default value if wasn't able to parse
int.TryParse( txtBankRegion.Text, out value );
objMEndorsement.BankRegion = bankRegion;

Then you can do the same with the other field.

Comments

0

Make objMEndorsement.BankRegion NULLable and:

if(!string.IsNullOrWhiteSpace(txtBankRegion.Text))
    objMEndorsement.BankRegion =  Convert.ToInt32(txtBankRegion.Text)

(This works if NULL is the initial value of the property objMEndorsement.BankRegion = Convert.ToInt32(txtBankRegion.Text))

Otherwise (property still have to accept NULL):

objMEndorsement.BankRegion = string.IsNullOrWhiteSpace(txtBankRegion.Text) ? null : Convert.ToInt32(txtBankRegion.Text);

Remember that your database field must be NULLable also (otherwise you will get a DB error when trying to persist NULL).

Comments

0

make it nullable type by converting the value type to nullable type and then send it to database

Comments

0

yes use ternary operator and assign corresponding values objMEndorsement.BankRegion = (txtBankRegion.Text.trim()) ? 0 : Convert.ToInt32(txtBankRegion.Text)

1 Comment

You really need to provide an example along with this explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.