試圖填補組合框與數據庫中的數據和我使用的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();
}
}
}
}
}
代碼中的用戶和密碼只是臨時的。
你能否刪除不相關的代碼?請指出顯示錯誤的行並僅包含相關片段。謝謝 –
Out of theme - 你應該總是關閉/處置你的連接到數據庫 – MikkaRin
你真的需要這個類,這隻會導致問題,否則如果你使用它創建連接,否則不會有問題,最好使用'使用'聲明?!其他的事情不會使用DB級別。 http://stackoverflow.com/a/9707060/284240 –