绑定组合框与文本和值

时间:2016-12-20 16:14:24

标签: c# combobox

我填充combobox,因为我的问题是我想使用displaymembervaluemember我搜索的数据绑定但是所有示例都使用了没有数据绑定

    public void Pobulate_combobox()
    {
        string connstr = @"Data Source=ORCL; User Id=user; password=pwd;";
        string cmdtxt = @"SELECT  column1, 
                                  column2
                           FROM table
                            ORDER BY column1";

        using (OracleConnection conn = new OracleConnection(connstr))
        using (OracleCommand cmd = new OracleCommand(cmdtxt, conn))
        {
            conn.Open();

            using (OracleDataReader dr = cmd.ExecuteReader())
            {
                List<string> items = new List<string>();

                while (dr.Read())
                {
                    CBOfficeCode.Items.Add(dr.GetString(0));
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:3)

要使用DisplayMember和ValueMember属性,您需要设置组合的DataSource属性。最简单的方法是加载DataTable并将该实例用作DataSource

using (OracleConnection conn = new OracleConnection(connstr))
using (OracleCommand cmd = new OracleCommand(cmdtxt, conn))
{
    conn.Open();
    DataTable dt = new DataTable();
    dt.Load(cmd.ExecuteReader());
    CBOfficeCode.DataSource = dt;
    CBOfficeCode.DisplayMember = "Column1";
    CBOfficeCode.ValueMember = "Column2";
}