close
加入label和comboBox
加入類別 States.cs
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: }
測試
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: }
參考資料
全站熱搜
留言列表