[英]I'm getting an exception of InvalidCastException
我想從上一頁獲取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;
為什么?
好的,在瀏覽完您的代碼之后,您似乎想要獲取按鈕 id,以便您可以基於它處理一些代碼。 好吧,讓我澄清一下,頁面加載事件永遠不會為您提供導致發件人 object 回發的控件,即使它在您單擊按鈕時被觸發並回發,但它不會在發件人 object 中包含該控件的信息將其發布回來。
為此,您可能想從這個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
object。
否則,在您的情況下,合適且簡潔的方法是這樣做:
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();
}
}
}
希望對你有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.