我目前正在处理大学作业,在该作业中我无法从SQL Server数据库读取数据。我试图读取该Dentist Name
列,然后将这些名称添加到组合框。
但是,当我输入列名时会显示错误。
我的表被称为dentistInfo
与列Dentist ID
,Dentist Name
,Dentist Surname
,DOB
和Gender
。
最终,当我正确地完成阅读后,当从组合框中选择名称时,我希望能够填充其详细信息。
public partial class Dentist_Info : Form
{
Surgery mySurgery = new Surgery();
private SqlConnection conn;
private SqlCommand cmd;
private SqlDataAdapter da;
Surgery _formsSurgery;
public Dentist_Info(Surgery SurgeryToDisplay)
{
_formsSurgery = SurgeryToDisplay;
}
public void FillCombo()
{
SqlConnection conn = new SqlConnection(@"Data Source = GGJG; Initial Catalog = DentistDB; Integrated Security = True");
SqlCommand SelectCommand = new SqlCommand("SELECT * FROM DentistInfo", conn);
SqlDataReader myreader;
conn.Open();
try
{
myreader = SelectCommand.ExecuteReader();
while (myreader.Read())
{
string dname = myreader.GetString("Dentist Name");
comboBox1.Items.Add(dname);
}
conn.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
试试这个:我建议您在牙医名称中放置[],因为它在两个单词之间有一个空格,这可能会导致您出错,或者将名称从数据库更改为DentistName。
public void FillCombo()
{
SqlConnection conn = new SqlConnection(@"Data Source = GGJG; Initial Catalog = DentistDB; Integrated Security = True");
SqlCommand SelectCommand = new SqlCommand("SELECT * FROM DentistInfo", conn);
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(SelectCommand);
da.fill(ds);
foreach(DataRow dr in ds.Tables[0].Rows)
{
comboBox1.Items.Add(dr["[Dentist Name]"].ToString());
}
conn.Close();
}
按照添加,而不是使用conn.Open()和conn.Close(),作为第一个用户的答案,您可以将连接包围在using中,如下所示:
using(SqlConnection conn = new SqlConnection(@"Data Source = GGJG; Initial Catalog = DentistDB; Integrated Security = True"))
{
//your codes here no need for conn.Open() and conn.Close()
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句