我有一個包含幾個串列框的表單,由物件填充。其中一個串列框應該包含物件,但顯示一個句子,該句子是該物件的幾個屬性與中間單詞的串聯。
我已經使用覆寫 ToString 方法以不同的方式在另一個串列框中顯示同一個類。我嘗試使用資料系結,但它似乎不適合顯示包含物件屬性的句子。我在所述類中確實有一個方法,該方法旨在根據所需的屬性創建這句話,但我不能使用此方法填充串列框,因為串列框不包含物件。
如何用物件填充此串列框,但讓它顯示所述資訊?
這是串列框的物件來自的類:
public House(string name, string adress, int nrOfStudents)
{
this.name = name;
this.adress = adress;
this.nrOfStudents = nrOfStudents;
taskpackages = new List<string>();
students = new List<Student>();
}
這個方法給出了哪些資訊應該顯示在串列框中的想法:
public string GetHouseNameStudentsTasks()
{
List<string> studentNames = GetStudentNames();
return this.name "\tTaskpackages: " string.Join(", ", taskpackages) "\tStudents: " string.Join(", ", studentNames);
}
應該執行操作的表單中的方法:
private void btnSaveHouse_Click(object sender, EventArgs e)
{
House selectedHouse = lbHouses.SelectedItem as House;
// several irrelevant functions
lbHousesAllInfo.Items.Add(selectedHouse);
// How to let lbHousesAllInfo contain House objects,
// but show the sentence described in the method above?
}
uj5u.com熱心網友回復:
向您的類添加屬性,House這將回傳適合您的每個串列框的顯示文本。例子,
class House
{
string name;
string address;
public House(string name, string address)
{
this.name = name;
this.address = address;
}
public string DisplayTextForListBox1
{
get
{
return $"{name}";
}
}
public string DisplayTextForListBox2
{
get
{
return $"{name} {address}";
}
}
}
您將不得不使用BindingSource組件(您可以在設計器中將此組件添加到表單中),為每個串列框控制元件使用一個,然后設定它們的DataSource屬性。
//
// bindingSource1
//
this.bindingSource1.DataSource = typeof(House);
//
// bindingSource2
//
this.bindingSource2.DataSource = typeof(House);
進行listBox1以下設定(您可以在 Visual Studio Designer 中進行)
this.listBox1.DataSource = this.bindingSource1;
this.listBox1.DisplayMember = "DisplayTextForListBox1";
對于listBox2做以下設定
this.listBox2.DataSource = this.bindingSource2;
this.listBox2.DisplayMember = "DisplayTextForListBox2";
將專案添加到系結源組件
private void Button1_Click(object sender, EventArgs e)
{
bindingSource1.Add(new House("Name1", "Address 1"));
bindingSource2.Add(new House("Name2", "Address 2"));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/489389.html
