2014-01-05 35 views
-5

我得到這個錯誤:出錯轉換字符串的SqlConnection

Cannot implicitly convert type string to System.Data.SqlClient.SqlConnection

這裏是我的C#代碼。

protected void Button1_Click(object sender, EventArgs e) 
{ 
    //login button 
    SqlConnection sqlConn = "Your Conncetion String"; //The error is here 
    sqlConn.Open(); 

    SqlCommand sqlComm = new SqlCommand(); 
    sqlComm.CommandText = String.Format("select * from users where [email protected] and [email protected]"); 
    sqlComm.Parameters.AddWithValue("@userName", TextBox1.Text.Trim()); 
    sqlComm.Parameters.AddWithValue("@password", TextBox2.Text.Trim()); 
    sqlComm.CommandType = CommandType.Text; 
    sqlComm.Connection = sqlConn; 
    SqlDataReader sqlRead = sqlComm.ExecuteReader(); 
    if (sqlRead.Read()) 
    { 
    Session["username"] = sqlRead["username"]; 
    } 

    // SqlRead.Close(); 

    //sqlConn1.Close(); 

    Response.Redirect("Default.aspx"); 

} 

有人可以解釋這個錯誤意味着什麼以及如何解決它?

+0

那麼你需要證明你的代碼! – meda

+2

有關您編寫的代碼問題的問題必須描述具體問題,並在問題本身中包含有效的代碼以再現問題。 –

+0

***顯示代碼***(vtc) – abelenky

回答

5

我知道你有一個連接字符串,並且想要一個SqlConnection對象。您可以使用它的構造函數:

string connString = "Your Conncetion String"; // valid connection string 
var sqlConn = new SqlConnection(connString); 

這將是最好的,如果你使用using關鍵字,因爲這會採取正確關閉連接的照顧。您還應該使用using作爲您的SqlReader

using (var sqlConn = new SqlConnection(connString)) 
{ 
    sqlConn.Open(); 
    // the rest of the code 
} 
1

變化

SqlConnection sqlConn = "Your Conncetion String"; 

SqlConnection sqlConn = new SqlConnection("Your Conncetion String"); 
0

應該

SqlConnection sqlConn = new SqlConnection("Your Conncetion String"); 

你可以從web.config中

閱讀
SqlConnection sqlConn = new 
SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString); 

now this error The name 'ConfigurationManager' does not exist in the current context

  1. 你必須添加一個引用到System.Configuration.dll

  2. 然後加入using System.Configuration;到您的類。

  3. 您現在可以訪問您的配置文件是這樣的:

    ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

+0

當我在瀏覽器中打開它時出現此錯誤 –

+0

初始化字符串的格式不符合從索引0開始的規範。 –

+0

現在此錯誤 名稱'ConfigurationManager'不存在於當前上下文 –