Norque Norque - 1 year ago 77
ASP.NET (C#) Question

Allowing a field being parsed to remain null if no input is read in

I'm reading in data from a web form using text boxes and inserting it into my SQL database. I had to parse the string input for 3 different text boxes to their matching data type in the database. I allow nulls in the database but when I execute the code, if I dont have a value in one of the boxes it fails when I reach the parse statement. How would I go about running the parse only if the textbox has content? Sorry I know it's probably a very easy solution but i cant seem to write anything that will compile.

** The ISBN is a MUST as it is the PK in my database so disregard my ISBN parse line. but for example, a book may have a 13digit ISBN (PK) but not have a 10 digit ISBN number, but if it does I'm required to store that in the DB

protected void Button1_Click(object sender, EventArgs e)

//Convert int to long for ISBN
long lng = long.Parse(txtISBN.Text);

//convert string to int for 10 digit isbn
int tenISBN = int.Parse(txtP1.Text);

//convert string to int for Vendor ISBN
int vendISBN;
vendISBN = Convert.ToInt32(txtVendorISBN.Text);
vendISBN = int.Parse(txtVendorISBN.Text);

//Table adapter object to Insert Data
DataSet1TableAdapters.TableBookTableAdapter bookTableAdapter;
bookTableAdapter = new DataSet1TableAdapters.TableBookTableAdapter();

DataSet1TableAdapters.CourseTableAdapter courseAdapter;
courseAdapter = new DataSet1TableAdapters.CourseTableAdapter();
courseAdapter.Insert(courseID: txtCourseID.Text, CourseTitle: txtCourseTitle.Text);

//Adapter insert Statement
bookTableAdapter.Insert(ISBN: lng, courseID: txtCourseID.Text, bookTitle: txtBookTitle.Text, Ancillary: txtAncillary.Text,
bookActive: bookActive, ActiveDate: activeCalendar.SelectedDate, InactiveDate: inactiveCalendar.SelectedDate, Author: txtAuthor.Text, Imprint: txtImprint.Text,
Publisher: txtPublisher.Text, EditionDate: txtEditionDate.Text, VendorISBN: vendISBN, p1: tenISBN, eBookAvailable: eBookAvailable, eISBN: txtEISBN.Text, Notes: txtNotes.Text);


Answer Source

if I dont have a value in one of the boxes it fails when I reach the parse statement.

You need to check first if your textbox has content, and you can do it like this:

  log = long.Parse(txtISBN.Text);

if the textbox content is null, or empty then the parse will not be done.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download