我正在制作无人驾驶飞行员日志。在日志中,在“飞行员”页面上,您可以从顶部的comboBox
中进行选择以选择您的飞行员。此数据来自项目中的SQL Server(.MDF
)数据库文件。选择试用后,数据库中的现有数据将填充表单的其余部分。我下面的代码成功查询了SQL Server数据库文件,并在FullName
中显示comboBox
,但现在我只是填写表格的其余部分。 (即FirstName
,LastName
,Address
,City
等。)
private void frmPilots_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Kevin\ownCloud\Programming\C# Projects\DroneLogbook\DroneLogbook\data.mdf;Integrated Security=True;Connect Timeout=30"))
{
SqlCommand sc = new SqlCommand("select Id,FullName from Pilots", conn);
conn.Open();
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(string));
dt.Columns.Add("FullName", typeof(string));
dt.Load(reader);
cmbExistingPilot.ValueMember = "Id";
cmbExistingPilot.DisplayMember = "FullName";
cmbExistingPilot.DataSource = dt;
conn.Close();
}
答案 0 :(得分:1)
根据所选select
和SqlDataReader
的值,您需要另一个ComboBox
语句来填写TextBoxes
。像这样:
SqlCommand command = new SqlCommand(
"SELECT FirstName, LastName FROM Pilots where Id = @Id;",
connection);
command.Parameters.AddWithValue("@Id",cmbExistingPilot.SelectedValue.ToString());
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
txtFirstName.Text = reader.GetString(0);
txtLastName.Text = reader.GetString(1);
//and...
}
}