0

I'm simply trying to do this, so later on when I save my values in the database they should be set to null incase the textfield is empty.

    int? DeliveryAdrID = null;
    int.TryParse(TextBoxDeliveryAdrID.Text, out DeliveryAdrID);

But I'm having an error parsing it along.

The above solution should later on make it possible to save empty textbox values in the database as "NULL" instead of 0.

The whole solution:

    int parsedValue;
    int? DeliveryAdrID = int.TryParse(TextBoxDeliveryAdrID.Text, out parsedValue) ? parsedValue : (int?)null;

    int id = Convert.ToInt32(GridViewData.SelectedValue.ToString());
                var data = tf.DBTable.Where(a => a.ID == id).FirstOrDefault();
                if (data == null)
                {
                    DBTable mt = new DBTable();
                    mt.Customer = TextBoxCustomer.Text;
                    mt.Country = TextBoxCountry.Text;
                    mt.DeliveryAdrID = parsedValue;
                    tf.DBTable.AddObject(mt);
                    tf.SaveChanges();
                }
                else
                {
                    data.Customer = TextBoxCustomer.Text;
                    data.Country = TextBoxCountry.Text;
                    data.DeliveryAdrID = parsedValue;
                    tf.SaveChanges();
              }
            }
pancake
  • 590
  • 7
  • 24
  • So, if your textbox is empty the DeiiveryAdrID should be null, but what should be the return value of this version of TryParse in this case? More specifically, when it should return false? – Steve May 20 '14 at 13:51
  • We need to specifically see the code that inserts into the database, not just the parsing, to figure out why 0 is appearing in the database instead of NULL. – vcsjones May 20 '14 at 14:06
  • I will update it in a moment – pancake May 20 '14 at 14:08
  • You need to pass in `DeliverAdrID`, not `parsedValue` – Chris Dunaway May 20 '14 at 14:17

1 Answers1

1

You cannot give a nullable int to int.TryParse. It must be an int. What you are trying to do can be accomplished like so:

int parsedValue;
int? DeliveryAdrID = int.TryParse(TextBoxDeliveryAdrID.Text, out parsedValue) ? parsedValue : (int?) null;
vcsjones
  • 138,677
  • 31
  • 291
  • 286
  • Hi, Thanks for you answer, your solution works fine, but it still adds 0 instead of NULL. I know you can't parse anything besides a number. Is there anyway possible to make empty values equals NULL instead of 0? – pancake May 20 '14 at 13:56
  • @MishMish That doesn't sound like it is related to these lines of code, but rather with how you are calling out the database. If you update your question to include the "insert into the database" part, we can examine that. – vcsjones May 20 '14 at 13:57
  • 1
    @MishMish - You need to pass in `DeliverAdrID`, not `parsedValue` – Chris Dunaway May 20 '14 at 14:16