简体   繁体   中英

Unexpected FormatException

I am trying to delete items from a list, however I want the page to display a message "there are not items left in the catalogue" once all items have been deleted. My try/catch code seems to work, however I receive an error FormatException was unhandled by usercode for the [int id = Int32.Parse(txtID.Text);] line of code.

I would appreciate if someone could help me.

Thanks in advance.

    public partial class DeleteBook : System.Web.UI.Page
    {
    public Catalogue catalogueInstance = new Catalogue();

    //Filepath for json file
    const string FILENAME = 
    @"C:\Users\tstra\Desktop\19456932_CSE2ICX_Assessment_3\Bin\Books.json";


protected void Page_Load(object sender, EventArgs e)
{
    string jsonText = File.ReadAllText(FILENAME);



    // reading data contained in the json filepath

    //convert objects in json file to lists
    catalogueInstance = JsonConvert.DeserializeObject<Catalogue>(jsonText);

    if (IsPostBack) return;

    ddlDelete.DataSource = catalogueInstance.books;
    ddlDelete.DataTextField = "title";
    ddlDelete.DataValueField = "id";

    //binding the data to Drop Down List
    ddlDelete.DataBind();
   }

   protected void ddlDelete_SelectedIndexChanged(object sender, EventArgs e)
    {
    Book b = catalogueInstance.books[ddlDelete.SelectedIndex];
    txtID.Text = b.id.ToString();
    txtTitle.Text = b.title;
    txtAuthor.Text = b.author;
    txtYear.Text = b.year.ToString();
    txtPublisher.Text = b.publisher;
    txtISBN.Text = b.isbn;
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {   
    int id = Int32.Parse(txtID.Text);
    Book book = catalogueInstance.books.SingleOrDefault(b => b.id == id);
    //catalogueInstance.books.Remove(book);

    catalogueInstance.books.RemoveAt(ddlDelete.SelectedIndex);

    ddlDelete.SelectedIndex = 0;
    ddlDelete_SelectedIndexChanged(ddlDelete, new EventArgs());

    if (book != null)
    {

    book.title = txtTitle.Text;
    book.year = Int32.Parse(txtYear.Text);
    book.author = txtAuthor.Text;
    book.publisher = txtPublisher.Text;
    book.isbn = txtISBN.Text;

    string jsonText = JsonConvert.SerializeObject(catalogueInstance);
    File.WriteAllText(FILENAME, jsonText);
    }
    txtSummary.Text = "Book ID of " + id + " has Been deleted from the 
    Catalogue" + Environment.NewLine;

    try
    {
        File.ReadAllText(FILENAME);

    }
    catch (FileNotFoundException)
    {

        txtSummary.Text = "There are no items in the Catalogue";

    }
    }
    }

Its seems this question boils down to parsing an int

Int32.Parse Method

Converts the string representation of a number to its 32-bit signed integer equivalent.

FormatException : Value is not in the correct format.

You need to be more defensive, textboxes can contain anything, users can type anything

Always try to use Int32.TryParse

Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the operation succeeded.

Example

bool result = Int32.TryParse(value, out number);
if (result)
{
   Console.WriteLine("Converted '{0}' to {1}.", value, number);         
}
else
{ 
   Console.WriteLine("Attempted conversion of '{0}' failed.", 
                           value == null ? "<null>" : value);
}

This is all to say, if you are going to parse something, its best to be defensive about it.

Also debugging is a vital tool for writing software. You could have probably worked out and solved your problem by examining your code while its running. You might want to have a read through the following

Navigating through Code with the Debugger

Using Breakpoints

Update

For a more solution centric example, anywhere you use something like this

int id = Int32.Parse(txtID.Text);

You should really do something like this

int id;

if(!Int32.TryParse(txtID.Text, out Id))
{
   //Let the user know about the in correct values
   // example
   MessageBox.Show("hmmMMm, Entered the wrong value you have, Fix it you must - Yoda");
   return;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM