填充组合框并在文本中显示 [英] populating the combobox and displaying in the text

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

问题描述

填充combox并在组合框中显示值
例如如果我在组合框中选择名称,则相应的ID应显示在文本框中.有人知道吗?我正在学习C#.我尝试过可以让任何人检查以下代码.

populating the combox and displaying the value in the combobox
for eg. if I choose name in the combobox the corresponding ID should display in the text box . Do anybody know? I am learning c#. I tried it can anybody examine the following code.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace DBExample
{
    public partial class Form1 : Form
    {
        private OleDbConnection dbConn; // Connection object
        private OleDbCommand dbCmd;     // Command object
        private OleDbDataReader dbReader;// Data Reader object
        private Member aMember;
        private string sConnection;
        // private TextBox tb1;
        // private TextBox tb2;
        private string sql;
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                // Construct an object of the OleDbConnection
                // class to store the connection string
                // representing the type of data provider
                // (database) and the source (actual db)
                sConnection =
                    "Provider=Microsoft.Jet.OLEDB.4.0;" +
                    "Data Source=c:member.mdb";
                dbConn = new OleDbConnection(sConnection);
                dbConn.Open();
                // Construct an object of the OleDbCommand
                // class to hold the SQL query. Tie the
                // OleDbCommand object to the OleDbConnection
                // object
                sql = "Select * From memberTable Order " +
                      "By LastName , FirstName ";
                dbCmd = new OleDbCommand();
                dbCmd.CommandText = sql;
                dbCmd.Connection = dbConn;
                // Create a dbReader object
                dbReader = dbCmd.ExecuteReader();
                while (dbReader.Read())
                {
                    aMember = new Member
                            (dbReader["FirstName"].ToString(),
                             dbReader["LastName"].ToString(),
                             dbReader["StudentId"].ToString(),
                             dbReader["PhoneNumber"].ToString());
                    // tb1.Text = dbReader["FirstName"].ToString();
                    // tb2.Text = dbReader["LastName"].ToString();
                    // tb1.Text = aMember.X().ToString();

                    //tb2.Text = aMember.Y(aMember.ID).ToString();
                    this.comboBox1.Items.Add(aMember.FirstName.ToString());

                    // this.listBox1.Items.Add(aMember.ToString());
                    // MessageBox.Show(aMember.ToString());
                    // Console.WriteLine(aMember.ToString());
                }
                dbReader.Close();
                dbConn.Close();
            }
            catch (System.Exception exc)
            {
                MessageBox.Show("show" + exc);
            }
        }
        private void DbGUI_Load(object sender, EventArgs e)
        {
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.textBox1.Text = comboBox1.SelectedItem.ToString();
            //textBox2.Text = string.Empty;
            foreach (var Item in comboBox1.Items);
            textBox2.Text += aMember.ID.ToString();
            //MessageBox.Show("read one record");
        }
        private void textBox2_TextChanged(object sender, EventArgs e)
        {
        }
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
        }
    }
}

推荐答案

您编写它的方式将永远无法找到ID.原因是在创建新的Member对象之后,您没有维护对它的引用.您已在comboBox中添加了一个项目,但仅添加了字符串的克隆.

因此,有两种方法可以做到这一点.一种是重写Member类本身的ToString方法.如:

The way that you''ve written it, you will never be able to find out the id. The reason is that after you created the new Member object, you didn''t maintain the reference to it. You added an item to the comboBox, but you just added a clone of the string.

So there are a couple of ways to do this. One is to override the ToString method of the Member class itself. As in:

class Member
{
  //other properties and methods

  protected override string ToString()
  {
    return this.FirstName;
  }
}



然后,不像在this.comboBox1.Items.Add(aMember);中那样添加Member对象,而不是将aMember.FirstName.ToString()添加到ComboBox中.然后,当一个项目被选中,你可以只设置<8>到.并且,combobox将使用ToString方法来设置所选文本和每个下拉菜单的文本.

或者,您可以使用BindingList<t></t>.在这种情况下,您将创建一个新列表,例如:



Then, instead of adding aMember.FirstName.ToString() to the ComboBox, you add the Member object as in this.comboBox1.Items.Add(aMember);. Then, when an item is selected you could just set the TextBox to ((Member)(comboBox1.SelectedItem)).ID. And, the combobox will use the ToString method to set the selected text and the text for each drop down.

Or, you could use a BindingList<t></t>. In that case, you create a new list like:

BindingList<Member> comboBoxList = new BindingList<Member>();


然后将新项目添加到BindingList.

然后,按如下所示设置comboBox1绑定属性:


Then add the new items to the BindingList.

Then, you set the comboBox1 binding properties as in:

comboBox1.DataSource = comboBoxList;
comboBox1.DisplayMember = "FirstName";
comboBox1.ValueMember = "ID";


(您只需要确保FirstName和ID实际上是属性,而不仅仅是公共字段即可.)

然后在SelectedIndexChanged事件中,将TextBox Text字段设置为comboBox1.SelectedValue.ToString().


(You just have to make sure that FirstName and ID are actually properties and not just public fields.)

Then in the SelectedIndexChanged event, you set the TextBox Text field to comboBox1.SelectedValue.ToString().


就像您知道如何从数据库中获取数据一样,只需说明您需要做什么.很抱歉,我还没有输入实际的代码,因为实际上是从手机中发送此代码的,因此格式设置很棘手.
为包含名称的组合框创建一个新的事件处理程序方法.处理程序应处理所选索引已更改"事件.
在此方法中,您将创建一个sql代码以获取与所选名称匹配的id.类似于>从[表名]中选择id,其中name =''"+ combobox1.Text +"''<< br mode ="hold"/>您可以通过命令文本将此sql传递给oleDbCommand对象属性.
然后,您可以通过方法命令执行查询.ExecuteReader()
;
使用reader对象将ID显示到文本框中

Reader.Read();
textbox1.text = reader [0] .ToString();
Looks like you know how to get data from a database so i''ll just state what you need to do. Am sorry I haven''t put real code coz am actually sending this from my phone so formating is tricky.
Create a new event handler method for the combo box that contains names. The handler should handle the "Selected Index Changed" event.
Within this method you''ll create an sql code to get the id that matches the selected name. Something like >select id from [table name] where name='' " + combobox1.Text + " '' <<br mode="hold" />you pass this sql into the oleDbCommand object via the command text property.
You then perform a query through the method command.ExecuteReader()
;
use the reader object to display the id into a textbox

Reader.Read();
textbox1.text=reader[0].ToString();


''''这将在您的组合框中插入类
''您的数据库包含一个borad表和一个class表
''取决于boardid类将从数据库中选择.
''_cmbclass-这是您的组合框名称
''通过任何boardid


''This will insert class in your combo box
''your database contain one borad table and one class table
''depending on boardid class will selected from database.
'' _cmbclass-This is your combo box name
''pass any boardid


Private Function getClass(ByVal _cmbclass As ComboBox, ByVal boardID As String) As String
       Dim ClassDataSet As New DataSet
       Dim c_adapter As OleDb.OleDbDataAdapter
       If conn.State = ConnectionState.Closed Then
           'connection()
           conn.Open()
           commd.CommandText = "select className,ClassID from cc_class where BoardID = " & boardID & ""
           commd.Connection = conn
           c_adapter = New OleDb.OleDbDataAdapter(commd)
           c_adapter.Fill(ClassDataSet, "cc_class")
           _cmbclass.DataSource = ClassDataSet.Tables(0)
           _cmbclass.ValueMember = "ClassID"
           _cmbclass.DisplayMember = "className"
           conn.Close()
       End If
       Return getClass
   End Function


''所有数据将填充到您的组合框中
''添加以下代码以在您的文本框中获取ID

textbox1.text = comboBox1.ValueMember


''all the data will fill in your combo box
''Add the following code to get id in your text box

textbox1.text=comboBox1.ValueMember


这篇关于填充组合框并在文本中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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