我正在创建一个从数据库中提取数据并提供两个组合框的表单。ComboBox1 以“名字姓氏”格式显示员工姓名。ComboBox2 以“Last, First”格式显示员工姓名。这些名字毫无困难地被拉进组合框。
我试图弄清楚如何做的是,一旦用户从任一下拉框中选择一个名称,它将根据来自查询的其他信息填充某些文本框,例如 textBox1、textBox2。
我试图使用
textBox1.Text = comboBox1.SelectedItem;
但是,我收到一条错误消息:无法将类型“对象”隐式转换为“字符串”。存在显式转换(您是否缺少演员表?)
这是我当前的代码。我故意省略了对数据库的连接查询等。
public partial class Employees : Form
{
public Employees()
{
InitializeComponent();
//Connect to database for Employees Table Headers
SqlConnection myConnection = new SqlConnection(@"Server=Server...");
try {
myConnection.Open();
string SqlDataPull = String.Format("SELECT * FROM Employees WHERE Lname IS NOT NULL {0} ORDER By Lname", (checkBox1.Checked ? "AND Active='Y'" : ""));
SqlCommand cmd = new SqlCommand(SqlDataPull, myConnection);
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
string strEmployee = String.Format("{0} {1}", dr["Fname"], dr["Lname"]);
comboBox1.Items.Add(strEmployee);
textBox1.Text = comboBox1.SelectedItem;
string strEmployee2 = String.Format("{0}, {1}", dr["Lname"], dr["Fname"]);
comboBox2.Items.Add(strEmployee2);
}
} catch (Exception e) {
MessageBox.Show(e.ToString());
} finally {
if (myConnection != null) {
myConnection.Dispose();
}
}
}
private void button1_Click(object sender, EventArgs e)
{
Main myNewForm = new Main();
myNewForm.Show();
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
Reports myNewForm = new Reports();
myNewForm.Show();
this.Close();
}
}