2011-08-31 47 views
-4
if (lblevent.Text == Request.QueryString["name"]) 
{ 
     string EventName = Request.QueryString["name"]; 
     const string SQL = "SELECT SMS FROM Event WHERE EventName = @EventName"; 

     using (SqlConnection con = new SqlConnection(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true")) 
     using (SqlCommand Command = new SqlCommand(SQL, con)) 
      Command.Parameters.Add("@EventName", EventName);      
      { 
       con.Open();//at here the "con" has an error it says:"'con' does not exist on current context." 
      } 
} 

其實我已經在上面的代碼中聲明瞭一個sqlconnection(con)int,但它沒有讀取它。請人幫忙..謝謝con.open有一個錯誤。我有一個連接錯誤我的代碼看起來像這樣

回答

3

這就是問題所在:

using (SqlConnection con = new SqlConnection("...")) 
using (SqlCommand Command = new SqlCommand(SQL, con)) 
Command.Parameters.Add("@EventName", EventName); 
{ 
    con.Open(); 
    ... 
} 

這相當於:

using (SqlConnection con = new SqlConnection("...")) 
{ 
    using (SqlCommand Command = new SqlCommand(SQL, con)) 
    { 
     Command.Parameters.Add("@EventName", EventName); 
    } 
} 
{ 
    con.Open(); 
    ... 
} 

在這一點上我希望這是顯而易見的什麼是錯的 - 當你調用con.Open你不再在using聲明正文中。你想要:

using (SqlConnection con = new SqlConnection("...")) 
using (SqlCommand Command = new SqlCommand(SQL, con)) 
{ 
    Command.Parameters.Add("@EventName", EventName);      
    con.Open(); 
    ... 
} 
+0

感謝您的回答。我仍在學習。所以對於我的無知感到抱歉 – user917145

1

也許你應該添加括號。

if (lblevent.Text == Request.QueryString["name"]) 
      { 
     string EventName = Request.QueryString["name"]; 
       const string SQL = "SELECT SMS FROM Event WHERE EventName = @EventName"; 
       using (SqlConnection con = new SqlConnection(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true")) 
        { 
        using (SqlCommand Command = new SqlCommand(SQL, con)) 
        { 
         Command.Parameters.Add("@EventName", EventName);      
         con.Open();//at here the "con" has an error it says:"'con' does not exist on current context." 
        } 
        } 
      } 
相關問題