[英]private variables resetting between methods c#
這可能是有史以來最大的noob問題,但我很困惑為什么我的私有變量,當它們在一個方法中設置時,在另一個方法中被重置。 我的代碼中有類似的東西:
namespace Project.Messages
{
public partial class Inbox : System.Web.UI.Page
{
private static int selectedIndex;
private static string messageIDString;
private static int messageID;
//select message to view
protected void viewMessage(object sender, GridViewCommandEventArgs e)
{
//get index
selectedIndex = MsgInbox.SelectedIndex;
if (int.TryParse(e.CommandArgument.ToString(), out selectedIndex))
{
//get selected dataKey, convert to a int
messageIDString = MsgInbox.DataKeys[selectedIndex].Value.ToString();
messageID = Convert.ToInt16(messageIDString);
}
}
//select message to delete
protected void delBTN_Click(object sender, EventArgs e)
{
SqlCommand com = new SqlCommand("DELETE FROM Messages WHERE MessageID = @param1", conn);
conn.Open();
com.Parameters.AddWithValue("param1", messageID);
}
因此,如果我單擊一條消息,將設置messageID並顯示該消息。 當我點擊刪除之后的消息時,看起來該變量正在重置/與先前設置的值不同。 我是否需要使用靜態變量或其他東西來實現這一目標?
謝謝
這就是行為。 當有回發時,所有變量都將被重置並重新分配。 您可以使用會話或視圖狀態或將值存儲在頁面中的控件中,該控件已經是視圖狀態的一部分,例如在隱藏字段中
public int messageID
{
get
{
int retVal = 0;
if(ViewState["messageID"] != null)
Int32.TryParse(ViewState["messageID"].ToString(), out retVal);
return retVal;
}
set { ViewState["messageID"] = value; }
}
這是因為ASP.NET,而不是C#。 您需要在viewstate中保存變量。 請參閱: 在類中初始化的變量在頁面加載時丟失其先前的值
這是因為網絡是無國籍的。 以下是一些在頁面之間傳遞數據的方法。
ASP.net MVC: http : //msdn.microsoft.com/en-us/library/dd394711( v = vs.100) .aspx
ASP.net Webforms http://msdn.microsoft.com/en-us/library/6c3yckfw(v=VS.100).aspx
希望這可以幫助。
您還可以使用Session對象來存儲請求之間所需的信息。 例如: Session["messageIdString"]=value
欲了解更多信息: http : //msdn.microsoft.com/en-us/library/ms178581(v = vs.100).aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.