意外的FormatException

时间:2018-05-16 03:14:28

标签: c# asp.net

我正在尝试从列表中删除项目,但是我希望页面在删除所有项目后显示“目录中没有项目”的消息。 我的try / catch代码似乎有效,但是我收到错误FormatException未被user int为[int id = Int32.Parse(txtID.Text);]代码行处理。

如果有人可以帮助我,我将不胜感激。

提前致谢。

    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";

    }
    }
    }

1 个答案:

答案 0 :(得分:4)

似乎这个问题归结为解析一个int

Int32.Parse Method

  

将数字的字符串表示形式转换为32位有符号   等价整数。

     

FormatException :值的格式不正确。

你需要更具防御性,文本框可以包含任何内容,用户可以输入任何内容

始终尝试使用Int32.TryParse

  

将数字的字符串表示形式转换为32位有符号   整数当量。返回值表示是否进行操作   成功了。

示例

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);
}

这就是说,如果你要解析一些东西,最好是防御它。

此外,调试是编写软件的重要工具。您可以通过在运行时检查代码来解决问题并解决问题。您可能希望阅读以下内容

Navigating through Code with the Debugger

Using Breakpoints

<强>更新

对于更加以解决方案为中心的示例,您可以在任何地方使用此类

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

你应该真的做这样的事情

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;
}