【原創】C#實現列表綁定

來源:互聯網
上載者:User

簡述:我在開發中有時候會遇到這樣的問題,如:我有這樣一張筆記本品牌表

分類ID

分類名稱

1001

宏基

1002

聯想

1003

華碩

1004

惠普

現在我需要把這些產品顯示給使用者,讓使用者做某種或多種選擇,而我在使用者做出選擇之後,我需要獲得的只是使用者選擇產品所對應的產品ID,客戶並不知道他所選擇的產品ID。在web開發方面似乎很多的清單控制項都已經提供了很好的支援,如CheckBoxList, RadioButtonList, DropDownList等web控制項都提供了兩個屬性(Value和Text),Value可以使用者存放產品ID,Text可以存放產品名稱,顯示給使用者。但是在Winform開發中,這樣一些清單控制項卻不像Web中那麼方便,如ComboBox和CheckedListBox清單控制項,它們只提供了綁定一個object對象。我需要實作類別似web的那個功能,我該怎麼做呢?描述的有點鬱悶,語言表述能力有待大大加強。下面來看舉例說明:

  1. 首先定義一個筆記本品牌結構,用於存放筆記本品牌ID和品牌名稱。

/// <summary>

    /// 筆記本類型

    /// </summary>

    /// <typeparam>Value實值型別</typeparam>

    /// <typeparam>Text實值型別</typeparam>

    public struct ComputerType<T, K>

    {

        private T m_value;

        /// <summary>

        /// Value值

        /// </summary>

        public T Value

        {

            get { return m_value; }

            set { m_value = value; }

        }

 

        private K m_text;

        /// <summary>

        /// Text值

        /// </summary>

        public K Text

        {

            get { return m_text; }

            set { m_text = value; }

        }

 

        public override string ToString()

        {

            return m_text.ToString();

        }

}

注意:需要重寫該ToString()

2.在品牌表中綁定即可,代碼如下:

ComputerType <int, string> computerType

foreach (string strType in typeArray)

{

     computerType  = new PacketType<int, string>();

          computerType.Value = “品牌名稱”;

     computerType.Text = “品牌ID”

     comboBox1.Items.Add(computerType);

}

PS:在這裡利用綁定對象的話,就變得非常靈活了。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.