views:

200

answers:

3

Hi , i'm developing a form to insert data in the Database (SQlServer 2005) i use Linq to Sql in WPF;

I have this database :

Column Name             Data Type          Allow Null
  CODE ID               Int(autoIncr)          No
  BoatName              Nvarchar(100)          No
  BoatType              Nvarchar(50)           yes
  NumberOfSeats         Int                    yes
 And so on...

Now when i insert a new record in my form if i leave empty the TextBox "txtNumberOfSeats" that refer to field "NumberOfSeat" in the database and when i click the button Save the database give me this error:"Input string was not in a correct format."

Why i cannot leave the field "NumberOfSeats " empty if i set up it in database AllowNull=Yes?

i post the code behind when i click the button Save to insert to new record in the database:

DataClassesDataContext dc = new DataClassesDataContext();
Boat_TBL boat = new Boat_TBL();
boat.BoatName = txtBoatName.Text;
boat.BoatType = txtBoatType.Text;
boat.NumberOfSeats = Int32.Parse(txtNumberOfSeats.Text);
dc.Boat_TBLs.InsertOnSubmit(boat);
dc.SubmitChanges;

DO you have any suggestion to work out this feature?

Thanks so much

Cheers

A: 

The call to Int32.Parse(...) fails when an empty string is passed to it. Provided that boat.NumberOfSeats is a nullable int, you should only set it when txtNumberOfSeats.Text is not an empty string.

David Andres
+2  A: 

You can pass null on the Data Access Layer when saving to your DB. e.g. try something like this:

if (String.isNullOrEmpty(txtNumberOfSeats.Text))
{
    NumberOfSeats = DBNull.Value;
}
waqasahmed
Hi waqasahmed,i tried your code but i receive this error:"Cannot implicitly convert type 'System.DBNull' to 'int?'"here is the code:if (String.isNullOrEmpty(txtNumberOfSeats.Text)){ boat.NumberOfSeats = DBNull.Value;// here i receive the error}Where i wrong?However thanks for your suggestion.Cheers
JayJay
int does not convert to DBNULL - You might try using "int?" - the question mark makes it nullable - then when you are adding parameters to your command you can put in logic to pass DBNull.Value instead of null.
DataDink
Yes.your advices was useful to work out this step.Thanks so much for your kind support.Cheers
JayJay
A: 

You can use the integer tryParse method and output parameter can be use as no of seats..

Jaswant Agarwal