Error pulling data into ComboBox2: 根据在ComboBox1中选择的索引

huangapple go评论60阅读模式
英文:

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

问题

我尝试从数据库中根据在ComboBox1中选择的索引提取数据到ComboBox2,但出现错误,原因是什么?

错误CS1503:2个参数:无法将“string”转换为“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);

        command.ExecuteNonQuery();

        var reader = command.ExecuteReader();


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

}
英文:

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();
    }

}

答案1

得分: 0

你在AddWithValue()中传递参数的顺序错误。

你的调用应该看起来像这样:

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

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);

答案2

得分: -1

我使用这个更改修复了错误。

comboBox1.SelectedValueChanged += new EventHandler(comboBox1_SelectedIndexChanged);

我忘记在我的form_load中添加这个代码块。

英文:

I fix the error with this change.

        comboBox1.SelectedValueChanged += new EventHandler(comboBox1_SelectedIndexChanged);

I forgot to add this code block to my form_load.

huangapple
  • 本文由 发表于 2023年7月18日 15:04:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76710238.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定