Search code examples
c#npgsql

Error pulling data into ComboBox2: According to the index selected in ComboBox1


I am trying to pull data from the database into ComboBox2 according to the index selected in ComboBox1, but I get an error, what is the reason?

Error CS1503 2 argument: Cannot convert from 'string' to 'NpgsqlTypes.NpgsqlDbType'

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
      
    string selectedValue = (string)comboBox1.SelectedValue;

    using (var connection = new NpgsqlConnection(""))
    {

        connection.Open();

        var command = new NpgsqlCommand("SELECT brand_name FROM brand WHERE material_type = Value", connection);

        command.Parameters.AddWithValue("Value", selectedValue , NpgsqlDbType.Char);

        command.ExecuteNonQuery();

        var reader = command.ExecuteReader();


        while (reader.Read())
        {
            comboBox3.Items.Add(reader["brand_name"]);
        }
 
        connection.Close();
    }

}

Solution

  • You passed the parameters of AddWithValue() in the wrong order.

    public NpgsqlParameter AddWithValue(
        string parameterName, 
        NpgsqlDbType parameterType, 
        object value)
    

    Your call should look something like this:

    command.Parameters.AddWithValue("Value", NpgsqlDbType.Char, selectedValue);