[C#.NET][VB.NET] ListBox 如何使用 資料繫結 / ListBox Use Data Binding

[C#.NET][VB.NET] ListBox 如何使用 資料繫結 / ListBox Use Data Binding

1.ListBox 使用繫結的方式一次只能顯示單行(Column)

2.ListBox 如何使用 資料繫結

  2.1.建立建立DataTable

  DataTable dt = new DataTable();

  2.2.載入OleDbDataReader

  dt.Load(dr);

  2.3.設定DataSource

  listBox1.DataSource = dt;
  listBox2.DataSource = dt;

  2.4.顯示成員

  listBox1.DisplayMember = "Id";

3.完整範例

private void Form1_Load(object sender, EventArgs e)
{
    FileName=Application.StartupPath +"\\input.xls";
    this.listBox1.DataSource = null;
    this.listBox1.Items.Clear();
    string qs = "select * from[" + SheetName + "$]";
    //連線字串
    cs =
            "Data Source=" + FileName + ";" +
            "Provider=" + ProviderName +
            "Extended Properties=" + ExtendedString +
            "HDR=" + Hdr +
            "IMEX=" + IMEX;
    //1.建立連線
    using(OleDbConnection cn = new OleDbConnection(cs))
    {
        //2.開啟連線
        cn.Open();
        //3.建立OleDbCommand物件
        using (OleDbCommand cmd = new OleDbCommand(qs, cn))
        {
            //4.建立OleDbDataReader物件
            using (OleDbDataReader dr = cmd.ExecuteReader())
            {
                //5.建立DataTable
                DataTable dt = new DataTable();
                //6.載入OleDbDataReader
                dt.Load(dr);
                //7.設定DataSource
                listBox1.DataSource = dt;
                listBox2.DataSource = dt;
                //8.顯示成員
                listBox1.DisplayMember = "Id";
                listBox2.ValueMember = "Name";
            }
        }
    }
}

4.範例下載

VB_ListView_DataBinding.rar

CS_ListView_DataBinding.rar

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo