从comboBox中选择值后填充文本框

时间:2019-04-03 18:53:55

标签: c# ms-access

从comboBox中选择一个值后,我试图填充文本框。

我的代码运行良好,运行它时没有任何错误,但是当我从comboBox中选择一个值时,它不会填充文本框。请参阅下面的代码。

    private OleDbConnection connection = new OleDbConnection();

    public Form1()
    {
        InitializeComponent();
        connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\ASUS\Documents\appointment2.accdb";
    }

    private void Lastname_SelectedIndexChanged(object sender, EventArgs e)
    {

        try
        {
            connection.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = connection;


            OleDbDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                string query = "select * from appointments where patientNo = '" + Lastname.Text + "' ";
                command.CommandText = query;

                Firstname.Text = reader["firstName"].ToString();
                patientNum.Text = reader["patientNo"].ToString();
                contactNum.Text = reader["contactNo"].ToString();

            }
            connection.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error" + ex);
        }
    }

2 个答案:

答案 0 :(得分:0)

我看到两个紧迫的问题:

  • 您将在发出CommandText方法后填充OleDbCommand对象ExecuteReader属性,这意味着不评估任何SQL语句。

    在发出ExecuteReader方法之前,应在 之前填充SQL语句,即:

    connection.Open();
    OleDbCommand command = new OleDbCommand();
    command.Connection = connection;
    command.CommandText = "select * from appointments where patientNo = '" + Lastname.Text + "' ";
    OleDbDataReader reader = command.ExecuteReader();
    while (reader.Read())
    {
        Firstname.Text = reader["firstName"].ToString();
        patientNum.Text = reader["patientNo"].ToString();
        contactNum.Text = reader["contactNo"].ToString();
    }
    connection.Close();
    
  • 您的SQL语句的where子句假设patientNo包含字符串数据,鉴于此字段的名称,该数据可能是错误的。

答案 1 :(得分:0)

只需找出问题所在。将我的Lastname.Text与比较错误的值,并修复了代码的排列。谢谢大家的帮助。

            connection.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = connection;
            command.CommandText = "select * from appointments where lastName = '" + Lastname.Text + "' ";
            OleDbDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                Firstname.Text = reader["firstName"].ToString();
                patientNum.Text = reader["patientNo"].ToString();
                contactNum.Text = reader["contactNo"].ToString();

            }     

            connection.Close();