2017-05-25 42 views
1

我有這個變量x。它包含我需要用來插入到另一個表中的ID。獲取在asp頁面加載中聲明的變量

protected void Page_Load(object sender, EventArgs e) 
{ 

    if (!Page.IsPostBack) 
    { 
     int x = Convert.ToInt32(Request.QueryString["id"]); 

     // Create Connection 
     SqlConnection con = new SqlConnection(conn); 
     // Create Command 
     SqlCommand cmd = new SqlCommand(); 
     cmd.Connection = con; 
     cmd.CommandText = "SELECT Name, FROM Hardware WHERE ID = " + x; 
     //Create DataReader 
     SqlDataReader reader; 
     con.Open(); 
     reader = cmd.ExecuteReader(); 
     dlstDetails.DataSource = reader; 
     dlstDetails.DataBind(); 
    } 
} 

我想在這裏訪問:

protected void btnBook_Click(object sender, EventArgs e) 
{ 
    //get x  
} 

我該怎麼辦呢?

+0

在你做其他事情之前,你應該先閱讀,理解並開始使用參數化查詢,然後才能訪問bobby表。 http://bobby-tables.com/這是廣泛開放的SQL注入。 –

+0

如果您想訪問查詢字符串值,您可以像訪問Page_Load一樣訪問它。當你在一個方法中聲明你的變量時,它們只對該方法可見。 –

回答

2

網絡是無狀態的,你可以從你的查詢字符串Request.QueryString["id"]拉它,或者使用Session這樣的:

int x = Convert.ToInt32(Request.QueryString["id"]); 
Session["X"] = x; 

然後:

protected void btnBook_Click(object sender, EventArgs e) 
{ 
    if(Session["X"] != null) 
    { 
     int x = Convert.ToInt32(Session["X"].ToString()); 
    } 
} 

你也應該知道,這種的代碼對於SQL Injection開放,您應該始終使用parameterized queries以避免SQL注入。

+0

我可能只是將它從查詢字符串中再次取代使用會話。 –

+0

@SeanLange是的。謝謝。我在我的回答中也提到了它。 –