close

image

加入label和comboBox

image

加入類別 States.cs

image

   1:  
   2: namespace UserControlState
   3: {
   4:     public class States
   5:     {
   6:         public int ID { get; set; }
   7:         public string Name { get; set; }
   8:     }
   9: }

 

使用者控制元件

1. 加入公開屬性SelectedState,將目前使用者選擇下拉選單的項目(SelectedItem)物件(object)回傳,

該數值回須強制轉型States或是利用as關鍵字

public States SelectedState
{
    get { return this.cboState.SelectedItem as States; }
}

2. ucStates_Load階段加入事件

利用List<States>資料型態 初始化comboBox選單內容

   1: public partial class ucStates : UserControl
   2:    {
   3:        public States SelectedState
   4:        {
   5:            get { return (States)this.cboState.SelectedItem; }
   6:        }
   7:  
   8:        public ucStates()
   9:        {
  10:            InitializeComponent();
  11:        }
  12:  
  13:        private void ucStates_Load(object sender, EventArgs e)
  14:        {
  15:            List<States> items = new List<States>();
  16:            items.Add(new States() { ID = 1, Name = "王X禾" });
  17:            items.Add(new States() { ID = 2, Name = "王X晴" });
  18:            items.Add(new States() { ID = 2, Name = "王X崧" });
  19:            items.Add(new States() { ID = 2, Name = "楊X惠" });
  20:            cboState.DataSource = items;
  21:            cboState.DisplayMember = "Name";
  22:            cboState.ValueMember = "ID";
  23:        }
  24:    }

 

Form1按鈕加入事件

   1: public partial class Form1 : Form
   2: {
   3:     public Form1()
   4:     {
   5:         InitializeComponent();
   6:     }
   7:  
   8:     private void button1_Click(object sender, EventArgs e)
   9:     {
  10:         MessageBox.Show(string.Format("ID = {0}, Name = {1}", ucStates1.SelectedState.ID, ucStates1.SelectedState.Name), "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
  11:     }
  12: }

 

測試

image

   1: private void button1_Click(object sender, EventArgs e)
   2:    {
   3:        MessageBox.Show(string.Format("ID = {0}, Name = {1}", ucStates1.SelectedState.ID, ucStates1.SelectedState.Name), "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
   4:    }

 

 

 

參考資料

1. C# Tutorial - How to Create and use User Control

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 me1237guy 的頭像
    me1237guy

    天天向上

    me1237guy 發表在 痞客邦 留言(0) 人氣()