如何在一个组合框中组合两个字段或列 [英] How to combine two fields or columns in one combo box

查看:65
本文介绍了如何在一个组合框中组合两个字段或列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

推荐答案

你好,

这里是一个例子.

using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private OleDbConnectionStringBuilder ConnectionBuilder = 
            new OleDbConnectionStringBuilder
            {
                Provider = "Microsoft.ACE.OLEDB.12.0",
                DataSource = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Database1.accdb"))
            };

        public DataTable LoadData()
        {
            DataTable dt = new DataTable();
            using (OleDbConnection cn = new OleDbConnection { ConnectionString = ConnectionBuilder.ConnectionString })
            {
                using (OleDbCommand cmd = new OleDbCommand { Connection = cn })
                {
                    cmd.CommandText = "SELECT TOP 5 Identifier, CompanyName, ContactName + ' - ' + ContactTitle As Contact FROM Customer";
                    cn.Open();
                    dt.Load(cmd.ExecuteReader());

                }
            }

            return dt;
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.DataSource = LoadData();
            comboBox1.DisplayMember = "Contact";
        }
        private void button1_Click(object sender, EventArgs e)
        {
            var row = ((DataRowView)comboBox1.SelectedItem).Row;
            MessageBox.Show(


""{row.Field< int>(标识符"))-{row.Field< string>(("CompanyName")}")); } } }
"{row.Field<int>("Identifier")} - {row.Field<string>("CompanyName")}"); } } }

ComboBox不支持开箱即用的列,因此我使用SQL别名来完成上述操作.

A ComboBox does not support columns out of the box so I used SQL aliasing to do the above.

我使用了MS-Access,但这将与aby数据源Excel,SQL-Server等一起使用,因为DataTable是这里的重点,而不是实际来源.

I used MS-Access but this will work with aby data source Excel, SQL-Server etc as the DataTable is the focus here not the actual source.


这篇关于如何在一个组合框中组合两个字段或列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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