[英]How can I access an object attribute in a form in c#?
我使用Items屬性將3個項目添加到窗體的comboBox中。 這些項目是:Item1,Item2,Item3。
當我在comboBox中選擇這3個項目中的任何一個時,我希望它顯示一個消息框,其中包含相應對象的第一個屬性的值。 例如,當我單擊Item1時,我希望它向我顯示對象a1的屬性“ CNP1”,當我單擊Item2時,我向我顯示對象a2的屬性CNP2,依此類推。
我想我可能會用創建的3個對象之一連接comboBox中的每個項目,而不僅僅是寫下這些名稱(Item1,Item2,Item3),但我不知道如何。
另外,由於我在同一項目中創建的類而創建了這3個項目。 在這個項目中,我只有一個類,一個窗體和主程序。
因此,如何將comboBox項連接到這些對象之一,尤其是僅使用該對象的一個屬性。 謝謝。
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace IncercareEX2015
{
public partial class PreluareDate : Form
{
ArrayList listaAbonati;
AbonatTelefonic ab;
public PreluareDate()
{
InitializeComponent();
double[] vectMin = new double[4] { 12, 15, 50, 20 };
AbonatTelefonic a1 = new AbonatTelefonic("CNP1", "Nume1", "Adresa1", "tel1", "tip1", vectMin);
double[] vectMin3 = new double[2] { 100, 130 };
AbonatTelefonic a3 = new AbonatTelefonic("CNP3", "Nume3", "Adresa3", "Tel3", "Tip3", vectMin3);
double[] vectMin2 = new double[3] { 200, 80, 150 };
AbonatTelefonic a2 = new AbonatTelefonic("CNP2", "Nume2", "Adresa2", "Tel2", "Tip2", vectMin2);
///GENERARE COLECTIE DE OBIECTE
ArrayList listaAbonati = new ArrayList();
listaAbonati.Add(a1);
listaAbonati.Add(a3);
listaAbonati.Add(a2);
listaAbonati.Sort();
}
private void comboBox1_nume_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (object o in listaAbonati)
MessageBox.Show(o.ToString());
}
}
}
假設您的代碼在選定索引更改時編譯並顯示o.ToString(),則您希望從使用ArrayList切換為通用List,在這種情況下,您可以使用List來訪問實體的屬性,而無需使用需要強制轉換事件處理程序。 這是代碼的相關部分:
List<AbonatTelefonic> listaAbonati;
public PreluareDate()
{
///GENERARE COLECTIE DE OBIECTE
listaAbonati = new List<AbonatTelefonic>();
listaAbonati.Add(a1);
listaAbonati.Add(a3);
listaAbonati.Add(a2);
listaAbonati.Sort();
}
private void comboBox1_nume_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (AbonatTelefonic at in listaAbonati)
MessageBox.Show(at.YourDesiredPropertyNameGoesHere);
}
您可以使用SelectedIndex
獲取AbonatTelefonic
。 希望對您有幫助。
private void comboBox1_nume_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1_nume.SelectedIndex != -1)
{
AbonatTelefonic at = (AbonatTelefonic)listaAbonati[comboBox1_nume.SelectedIndex];
MessageBox.Show(at.YourAttribute);
}
}
在您的AbonatTelefonic
類上添加public override string ToString()
並添加代碼return {first attrib variable};
適用於您的參考: https : //msdn.microsoft.com/zh-cn/library/ms173154(v=vs.80).aspx
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.