2016-08-22 43 views
-2

试图填补组合框与数据库中的数据和我使用的ExecuteReader如下,但是当我尝试实例我的连接它显示我的错误无法含蓄转化类型错误

无法隐式转换类型的错误

我的数据库连接类代码:

public class DBConnect 
{ 
     private SqlConnection connection; 
     private string servername = "10.1.76.109,1433"; 
     private string database = "EngLib"; 
     private string dbuser; 
     private string userpassword; 


     public DBConnect() 
     { 

     } 

     public void doDBConnect(string dbuserform, string userpasswordform) 
     { 
      dbuser = dbuserform; 
      userpassword = userpasswordform; 
     } 


     public void Initialize() 
     { 

     } 

     public bool openConnection() 
     { 
      string connectionString; 
      connectionString = "Server=" + servername + ";Database=" + database + ";user id=" + dbuser + ";Password=" + userpassword; 
      Console.WriteLine(connectionString); 
      connection = new SqlConnection(connectionString); 
      try 
      { 
       connection.Open(); 
       return true; 
      } 
      catch (SqlException ex) 
      { 
       switch (ex.Number) 
       { 
        case 0: 
         MessageBox.Show("Não é possível contactar o servidor. Entre em contato com o administrador"); 
         break; 

        case 18456: 
         MessageBox.Show("Usuário/Senha inválidos, tente novamente"); 
         break; 
       } 
       return false; 
      } 

} 

我的表单代码:

{ 
    public Form2() 
    { 
     InitializeComponent(); 
    } 

    public void Form2_Load(object sender, EventArgs e) 
    { 
     SqlDataReader rdr = null; 
     DBConnect sqlConnection; 
     sqlConnection = new DBConnect(); 
     sqlConnection.doDBConnect(dbuserform: "usertest", userpasswordform: "usertest"); 
     { 
      try 
      { 

       { 
        sqlConnection.openConnection(); 
        SqlCommand sqlCmd; 
        sqlCmd = new SqlCommand("SELECT Material FROM EngLib"); 
        sqlCmd.Connection = sqlConnection; 
        SqlDataReader sqlReader = sqlCmd.ExecuteReader(); 

        while (sqlReader.Read()) 
        { 
         comboBox1.Items.Add(sqlReader["Material"].ToString()); 
        } 

        sqlReader.Close(); 
       } 
      } 
      finally 
      { 
       // close the reader 
       if (rdr != null) 
       { 
        rdr.Close(); 
       } 
      } 
     } 
    } 
} 

代码中的用户和密码只是临时的。

+0

你能否删除不相关的代码?请指出显示错误的行并仅包含相关片段。谢谢 –

+0

Out of theme - 你应该总是关闭/处置你的连接到数据库 – MikkaRin

+0

你真的需要这个类,这只会导致问题,否则如果你使用它创建连接,否则不会有问题,最好使用'使用'声明?!其他的事情不会使用DB级别。 http://stackoverflow.com/a/9707060/284240 –

回答

1

我认为这个问题是在这里:

DBConnect sqlConnection; 
SqlCommand sqlCmd; 
sqlCmd.Connection = sqlConnection; 

SqlCommand预计ConnectionSqlConnection型的,但你指定你自己的类DBConnect

可能的修正:

暴露于DBConnectconnection属性,并使用它。

继承DBConnectSqlConnection

直接使用SqlConnection

附加说明:您不会在DBConnect级别内部处理SqlConnection,这可能会导致StackOverflowException。您应该执行IDisposable

+0

非常感谢你,那是问题,现在它已经解决了。 –

+0

很高兴帮助!如果这是问题,请接受答案。 –

相关问题