我正在尝试从列表中删除项目,但是我希望页面在删除所有项目后显示一条消息"there not item in the catalogue“。我的try/catch代码似乎可以工作,但是我收到一条错误消息,那就是int = Int32.Parse(txtID.Text);这行代码的用户代码没有处理FormatException。
如果有人能帮我,我将不胜感激。
提前谢谢。
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";
}
}
}发布于 2018-05-16 11:23:20
这个问题似乎可以归结为解析一个int
将数字的字符串表示形式转换为其等效的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
更新
对于更多以解决方案为中心的示例,您可以在任何地方使用以下内容
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;
}https://stackoverflow.com/questions/50361967
复制相似问题