如何在组合框中将所选项的值显示到给定的文本框中 [英] How to display value of selected items in combobox into given text box

查看:93
本文介绍了如何在组合框中将所选项的值显示到给定的文本框中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想如果组合框中的选定项目由数据库查询组合框项目的值,组合框中所选项目的结果将显示在文本框中



我尝试过:



/ *代码从访问数据库获取数据到组合框* /

I want if selected items in the combo box where the value of combo box item is queried by database, the result of selected item in combo box will show in text box

What I have tried:

/* code get data from access db into combo box */

private void GetProductsName()
      {
          try
          {
              OleDbConnection conn = new OleDbConnection();
              conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\xxx\Documents\RetailDatabse.accdb;Persist Security Info=False";
              conn.Open();

              OleDbCommand cmd = new OleDbCommand();
              cmd.Connection = conn;
              cmd.CommandText = "SELECT ProductName, ProductPrice FROM Products";
              OleDbDataReader reader = cmd.ExecuteReader();
              while (reader.Read())
              {
                  ItemNamecomboBox.Items.Add(reader["ProductPrice"].ToString() + "  " + reader["ProductName"].ToString());
                  //ItemNamecomboBox.Items.Add(reader["ProductPrice"].ToString());

              }

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





/ *显示来自所选组合框的数据,收到错误* /



/* showing data from selected combo box that get error */

private void ItemNamecomboBox_SelectedValueChanged(object sender, EventArgs e)
       {

           decimal productPrice = Convert.ToDecimal(ItemNamecomboBox.SelectedValue);
           UnitPricetextBox.Text = productPrice.ToString();

       }

推荐答案

试试这个



try this

ItemNamecomboBox.DisplayMember = "Text";
            ItemNamecomboBox.ValueMember = "Value";
            while (reader.Read())
            {
                ItemNamecomboBox.Items.Add(new { Text = reader["ProductPrice"].ToString() + "  " + reader["ProductName"].ToString(), Value = reader["ProductPrice"].ToString() });
            } 







private void ItemNamecomboBox_SelectedValueChanged(object sender, EventArgs e)
       {
           dynamic item = ItemNamecomboBox.SelectedItem;
           if (item != null)
           {
               string price = item.Value;
           }
       }


这篇关于如何在组合框中将所选项的值显示到给定的文本框中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆