[英]Get ComboBox selected value from a list which has two types of objects and the combobox is only showing one of them
我正在 Windows 窗體中構建 C# 應用程序。
我有一個車輛類和兩個派生類汽車和摩托車。
然后我將車輛保存到列表中。
現在我有一個表格,我只想顯示汽車或摩托車。 在主窗體中有一個按鈕“顯示汽車”和另一個按鈕“顯示摩托車”,它們會告訴另一個窗體要列出哪個(下面代碼中的“類型”變量)。
在展示表格中,我有一個ComboBox,它將顯示所有存在的汽車或摩托車(僅一個,而不是兩者),其中選擇一個並且有一個文本框,它將顯示那個信息。
要填充我使用的組合框:
foreach (Vehicle V in GetVehiclesList())
{
if (type == "Car")
{
if (V.WhatIsIt() == "Car")
{
combobox.Items.Add(V.GetVehicleName());
}
}
else if (type == "Motorbike")
{
if (V.WhatIsIt() == "Motorbike")
{
combobox.Items.Add(V.GetVehicleName());
}
}
}
注意:WhatIsIt() 返回一個帶有類名的字符串。
現在的問題是在組合框中獲取所選車輛以顯示該車輛的信息。
如果我想展示所有車輛,我會使用這個:
private void combobox_SelectedIndexChanged(object sender, EventArgs e)
{
VehicleToShow = GetVehiclesList()[combobox.SelectedIndex];
vehicle_name_textbox.Text = VehicleToShow.GetVehicleName();
// and goes on
}
它的作用是獲取所選組合框項的索引號,並獲取列表中具有相同位置號的車輛。 它起作用是因為車輛被添加到組合框中,其位置/索引與列表中的相同。 因此,它不適用於僅顯示其中之一(汽車或摩托車),因為列表中的位置編號將無法與組合框中的索引相等。
所以我使用了以下方法:
private void combobox_SelectedIndexChanged(object sender, EventArgs e)
{
VehicleToShow = null;
int carposition = 0;
int motorbikeposition = 0;
int comboboxindex = combobox.SelectedIndex;
foreach (Vehicle V in GetVehiclesList())
{
if (V.WhatIsIt() == "Car")
{
if (carposition == comboboxindex)
{
VehicleToShow = V;
}
else
{
carposition++;
}
}
else if (V.WhatIsIt() == "Motorbike")
{
if (motorbikeposition == comboboxindex)
{
VehicleToShow = V;
}
else
{
motorbikeposition++;
}
}
}
vehicle_name_textbox.Text = VehicleToShow.GetVehicleName();
// and goes on
}
雖然在我看來這應該是可行的,但在使用它時,它不會顯示來自組合框中所選車輛的信息。
我怎樣才能讓它工作?
注意:不能將每種車輛類型放在不同的列表中。 此外,搜索與所選值同名的對象列表也不是最佳選擇,因為如果它有兩輛同名的車輛,它將無法正常工作。 理想情況下,它與我嘗試使用的方法類似。
不要將對象的名稱添加到列表中。 改為添加實際對象本身; 然后combobox.SelectedItem
立即包含您需要的所有內容,根本不需要任何查找,因為它將是完整的對象。
數據的填寫:
this.combobox.Items.Clear();
foreach (Vehicle veh in this.GetVehiclesList())
{
// assuming "type" is a string variable filled up by some other selected value.
if (!String.Equals(type, typeof(veh).ToString()))
continue;
this.combobox.Items.Add(veh);
}
盡管 derloopkat 建議將type
保存為實際Type
以便您可以直接比較它們可能比字符串比較更有效。 避免在代碼中進行字符串比較; 對於一些可以在內部更優雅、更高效地完成的事情,它們通常是一個丑陋的程序員捷徑。
為了使它們正確顯示在列表中,只需在您的車輛類中添加ToString()
函數,該函數返回實際車輛名稱:
public override String ToString()
{
return this.GetVehicleName()
}
最后,要檢索選定的對象並更新您的 UI:
private void combobox_SelectedIndexChanged(Object sender, EventArgs e)
{
// "as" is a "try cast": if the object is not the expected type it will become null.
this.VehicleToShow = this.combobox.SelectedItem As Vehicle;
if (this.VehicleToShow == null)
return; // maybe add code to clear UI
this.vehicle_name_textbox.Text = this.VehicleToShow.GetVehicleName();
// fill in the rest
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.