繁体   English   中英

如何使用 combobox 中的数据库值填充文本框?

[英]How can I populate a textbox with database values from a combobox?

我是 C# 的新手,我正在尝试用来自所选 combobox 的数据填充多个文本框。我的主要 window 带有文本框和组合框,还有一个单独的 class 用于连接到数据库(我正在使用 XAMPP/PhpMyAdmin) . 我设法用数据库中的数据填充组合框,但我无法填充所选 combobox 中的文本框。我检查了其他问题和教程,但我设法实现的只是将主键放入文本框中,但我需要表格中的不同列,具体取决于文本框。

我从数据库中填充了 combobox:

void Completez_Combo_Furnizor()
{
    combo_furnizor = DB_Furnizori.Combo_Furnizor();
    comboBoxFurnizor.Items.Clear();
    comboBoxFurnizor.DataSource = combo_furnizor;
    comboBoxFurnizor.ValueMember = "id_furnizor";
    comboBoxFurnizor.DisplayMember = "nume";
}

我双击 combobox 并写入以下内容,但我只能得到主键(第一列)。 在文本框中,我需要获取第 7 列(这是一个 double 类型。

private void comboBoxFurnizor_SelectedIndexChanged(object sender, EventArgs e)
{
    textBoxPret.Text = comboBoxFurnizor.SelectedItem.ToString();
}

这是来自数据库 class (DB_Furnizori.cs),我在其中打开连接并对数据库进行多次查询。

public static DataTable Combo_Furnizor()
{
    conn.Open();
    MySqlCommand comboFurnizor = new MySqlCommand("SELECT * from furnizori ORDER BY nume", conn);
    MySqlDataAdapter adaptc = new MySqlDataAdapter(comboFurnizor);
    DataTable combo_furnizori = new DataTable();
    adaptc.Fill(combo_furnizori);
    conn.Close();
    return combo_furnizori;
}

请帮忙。

    private void comboBoxFurnizor_SelectedIndexChanged(object sender, EventArgs e)
    {
        ComboBox cmb = (ComboBox)sender;
//to get the selected Index
        int selectedIndex = cmb.SelectedIndex;

//to get the value 
        int selectedValue = (int)cmb.SelectedValue;

        ComboboxItem selectedItem = (ComboboxItem)cmb.SelectedItem;
    textBoxPret.Text =selectedItem .Text

    }

对于您的 SelectedIndexChanged 方法:

private void comboBoxFurnizor_SelectedIndexChanged(object sender, EventArgs e)

{
    textBoxPret.Text = comboBoxFurnizor.SelectedItem.ToString();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM