如何通过ComboBox整数筛选访问表

本文关键字:筛选 访问表 整数 ComboBox 何通过 | 更新日期: 2023-09-27 17:49:52

我已经将我的程序连接到访问数据库文件,当我选择组合框中的数字(1,2,3等)时,我想自动填充表单中的其他文本框。如果它是一个字符串。例如,如果我在组合框中选择字符串(例如name),它会自动填充其他文本框,但如果它是整数则不起作用。

我知道我必须转换成整型,但我不知道怎么做,因为我有一个查询:

private void iD_FurnizorComboBox_SelectedIndexChanged_1(object sender, EventArgs e)
{
    try
    {
        connection.Open();
        OleDbCommand command = new OleDbCommand();
        command.Connection = connection;
        string query;
        query = "select * from Furnizori where id_furnizor = '" + iD_FurnizorComboBox.Text + "'";
        command.CommandText = query;
        OleDbDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            numeTextBox.Text = reader["nume"].ToString();
            adresaTextBox.Text = reader["adresa"].ToString();
            localitateTextBox.Text = reader["localitate"].ToString();
            judetTextBox.Text = reader["judet"].ToString();
        }
        connection.Close();
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        connection.Close();
    }
}

我不知道在哪里将字符串解析为int..谢谢你! !

如何通过ComboBox整数筛选访问表

使用int.TryParse将字符串解析为int。您也有一些问题,如sql注入和不使用using -语句。

private void iD_FurnizorComboBox_SelectedIndexChanged_1(object sender, EventArgs e)
{
    int id_furnizor;
    if(!int.TryParse(iD_FurnizorComboBox.Text, out id_furnizor))
    {
        MessageBox.Show("id_furnizor is not a valid integer: " + iD_FurnizorComboBox.Text);
        return;
    }
    using(var connection=new OleDbConnection("Connection String"))
    {
        try
        {
            string query = @"select f.* 
                             from Furnizori f
                             where id_furnizor = @id_furnizor;";
            OleDbCommand command = new OleDbCommand(query, connection);
            command.Parameters.Add("@id_furnizor", OleDbType.Integer).Value = id_furnizor;
            connection.Open();
            OleDbDataReader reader = command.ExecuteReader();
            if (reader.Read())
            {
                numeTextBox.Text = reader.GetString(reader.GetOrdinal("nume"));
                adresaTextBox.Text = reader.GetString(reader.GetOrdinal("adresa"));
                localitateTextBox.Text = reader.GetString(reader.GetOrdinal("localitate"));
                judetTextBox.Text = reader.GetString(reader.GetOrdinal("judet"));
            }
        } catch (Exception ex)
        {
            throw;  // redundant but better than throw ex since it keeps the stacktrace
        }
    }// not necessary to close connection, done implicitly 
}