【问题标题】:I'm getting an exception of InvalidCastException我遇到了 InvalidCastException 异常
【发布时间】:2020-08-17 07:37:45
【问题描述】:

我想从上一页获取asp 按钮 ID,但遇到了异常。 这是我的C#代码

public partial class ADD_MOBILE : System.Web.UI.Page
{
        string BUTN_ID;
        protected void Page_Load(object sender, EventArgs e)
        {
            Button button = (Button)sender;
            string BUTTON_CLICKER_ID = button.ID;
            BUTN_ID = BUTTON_CLICKER_ID;
        }
        protected void saveMOBILE_Click(object sender, EventArgs e)
        {
            if(BUTN_ID == "samsung"){ ... }        
        }
}

此时我遇到异常Button button = (Button)sender; 为什么?

【问题讨论】:

标签: c# asp.net exception webforms web-controls


【解决方案1】:

好的,在浏览完您的代码之后,您似乎想要获取按钮 ID,以便您可以根据它处理一些代码。好吧,让我澄清一下,页面加载事件永远不会为您提供导致发件人对象回发的控件,即使它在您单击按钮时被触发并回发,但它不会在发件人对象中包含该控件的信息把它发回来了。

为此,您可能想从James Johnson 的回答中使用这种方法来了解哪个控件导致回发:

/// <summary>
/// Retrieves the control that caused the postback.
/// </summary>
/// <param name="page"></param>
/// <returns></returns>
private Control GetControlThatCausedPostBack(Page page)
{
    //initialize a control and set it to null
    Control ctrl = null;

    //get the event target name and find the control
    string ctrlName = page.Request.Params.Get("__EVENTTARGET");
    if (!String.IsNullOrEmpty(ctrlName))
        ctrl = page.FindControl(ctrlName);

    //return the control to the calling method
    return ctrl;
}

这将返回您可以进一步深入研究的 Control 对象。

否则,在您的情况下,合适且简洁的方法是这样做:

public partial class ADD_MOBILE : System.Web.UI.Page
{
        string BUTN_ID; // I do not think it is necessary here.
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void saveMOBILE_Click(object sender, EventArgs e)
        {
            Button button = (Button)sender;
            if(button is null) return; // you can use == instead of keyword 'is'

            if(button.ID.Equals("samsung"))
            {
                 // DoStuff();
            }        
        }
}

希望对你有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多