如何在文本框中检索组合框选定项目的记录
本文关键字:项目 记录 组合 检索 文本 | 更新日期: 2023-09-27 18:35:29
我想通过组合框中选择的名称显示成员的所有详细信息。我正在尝试在给定的代码下面
private void cbSearchByName_SelectedIndexChanged(object sender,EventArgs e)
{
try
{
//int RowsAffected = 0;
DataAccess oDataAccess = new DataAccess();
con.Open();
//showing flat number of selected member by name
oDataAccess.cmd.CommandText = "SELECT FlatNo FROM MemberInfo where MemberName='" + cbSearchByName.Text + "'";
oDataAccess.cmd.Connection = con;
tbOwnerName.Text = ((string)cmd.ExecuteScalar());
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
我知道
您需要从memberinfo表中获取所有列记录并在UI中显示它们。为此,您需要使用 ExecuteReader 而不是 ExecuteScalar。我已经在下面的代码中实现了执行阅读器
private void cbSearchByName_SelectedIndexChanged(object sender,EventArgs e)
{
try
{
//int RowsAffected = 0;
DataAccess oDataAccess = new DataAccess();
using(SqlConnection connection = con )
{
connection.Open();
//showing flat number of selected member by name
oDataAccess.cmd.CommandText = "SELECT Top 1 Name,City FROM MemberInfo where MemberName='" + cbSearchByName.Text + "'";
oDataAccess.cmd.Connection = con;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
tbOwnerName.Text = dr["Name"].ToString();
tbOwnerCity.Text = dr["City"].ToString();
//similarly store other column values in respective text boxes or wherever you need to get it displayed.
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}