我试图从 TextBox 类派生一个名为 NumBox 的自定义类,并为这个类创建一个 setter 和 getter,但是当我运行我的程序时,我得到一个运行时异常“FormatException 未被用户代码处理”。在我看来,这与 this.Text 不是整数有关,但我的程序的输入是一个 int。错误发生在以下行: return Convert.ToInt16(this.Text);
谢谢你的帮助!
请在下面找到我的代码:default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<glm:numbox ID="NumBox1" runat="server" Style="position: relative" />
<asp:Button ID="Button_SquareIt" runat="server" Style="position: relative"
Text="Square It" onclick="Button_SquareIt_Click" />
</div>
</form>
</body>
</html>
网络配置
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<pages>
<controls>
<add tagPrefix="glm" namespace="GLM"/>
</controls>
</pages>
</system.web>
</configuration>
App_Code/NumBox.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for Class1
/// </summary>
///
namespace GLM
{
public class NumBox : TextBox
{
public NumBox()
{
//
// TODO: Add constructor logic here
//
}
public int Num
{
set
{
this.Text = value.ToString();
}
get
{
return Convert.ToInt16(this.Text);
}
}
}
}
默认.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
GLM.NumBox n = new GLM.NumBox();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button_SquareIt_Click(object sender, EventArgs e)
{
n.Num = n.Num * n.Num;
}
}