У меня есть программа, в которой я использую комбинированные списки для навигации по вложенной структуре данных.эти комбинированные списки должны использовать свойства из структуры данных в качестве элементов отображения.
Я связываю элементы для всех комбинированных списков в конструкторе моей формы
public frmWeatherManager()
{
InitializeComponent();
cmbLocationSelect.DisplayMember = "NameCmbBoxInterface";
cmbLocationSelect.ValueMember = "YearCmbBoxInterface";
cmbYearSelect.DisplayMember = "NumCmbBoxInterface";
cmbYearSelect.ValueMember = "this";
cmbMonthSelect.DisplayMember = "IdCmbBoxInterface";
cmbMonthSelect.ValueMember = "this";
}
NameCmbBoxInterface и другие подобные свойстваЯ просто обязан выступать в качестве доверенного лица для частного участника.
private string Name;
private string StreetName;
private string County;
private string PostCode;
private double Latitude;
private double Longitude;
private Year[] Years;
public string NameCmbBoxInterface
{
get
{
return Name;
}
set
{
Name = value;
}
}
Мне пришлось сделать это из-за произвольного ограничения, наложенного на меня моим лектором.Мне не разрешено использовать какие-либо «встроенные» функции.Это означает, что я должен написать геттеры и сеттеры самостоятельно, и я не могу использовать списки или методы, такие как .contains ().
Я заполняю структуру данных двумя способами:
первый способ - это гдеЯ генерирую случайные данные.
private void btnPopulate_Click(object sender, EventArgs e)
{
Locations = new Location[3];
Locations[0] = new Location("location1", "england", "street1", "postcode1", 0.55, 2.74, year_populate("Location1"));
Locations[1] = new Location("location2", "england", "street2", "postcode2", 1.45, -0.70, year_populate("Location2"));
Locations[2] = new Location("location3", "england", "street3", "postcode3", 7.37, -1.40, year_populate("Location3"));
cmbLocationSelect.DataSource = Locations;
}
Это работает нормально, и в выпадающем списке выбора местоположения правильно отображаются "location1", "location2", "location3".
У меня есть другая функция, которая читает данныеиз файла:
private void btnReadFile_Click(object sender, EventArgs e)
{
System.IO.StreamReader file = new System.IO.StreamReader(txtFilePath.Text);
//establish the number of locations to be parsed.
int locationcount = int.Parse(file.ReadLine());
//initalize locations array to the required size
Locations = new Location[locationcount + 1];
for (int i=0; i < locationcount; i++)
{
//begin location parse
//i is used to control access to location array
//extract data and sort into containers ready for insertion into data structure.
string locationName = file.ReadLine();
string streetName = file.ReadLine();
string county = file.ReadLine();
string postCode = file.ReadLine();
double latitude = double.Parse(file.ReadLine());
double longitude = double.Parse(file.ReadLine());
//establish number of years in location to be parsed
//must be done first so that location object's year array knows how large it needs to be
int yearcount = int.Parse(file.ReadLine());
//create new location object inside array.
Locations[i] = new Location(locationName, streetName, county, postCode, latitude, longitude, yearcount);
for (int R=0; R < yearcount; R++)
{
//begin year parse
string desc = file.ReadLine();
int yearid = int.Parse(file.ReadLine());
//create current year object
Year thisyear = new Year(yearid, desc);
for(int M=0; M < 12; M++)
{
//begin month parse
int monthid = int.Parse(file.ReadLine());
double maxtemp = double.Parse(file.ReadLine());
double mintemp = double.Parse(file.ReadLine());
int frostdays = int.Parse(file.ReadLine());
double rainfall = double.Parse(file.ReadLine());
double sunshine = double.Parse(file.ReadLine());
//read out useless year id line unless we are on the last loop
if (M != 11)
file.ReadLine();
//create current month object
Month thismonth = new Month(monthid, frostdays, maxtemp, mintemp, rainfall, sunshine);
//add month in question to the correct place in the year object.
thisyear.SetMonth(thismonth, M);
}
//similarly add year to location.
Locations[i].SetYear(thisyear, R);
}
}
file.Close();
//now that we are all done. Bind the data source of the combo box
cmbLocationSelect.DataSource = Locations;
}
В этом случае происходит сбой.Поле со списком выбора местоположения отображает оценку .tostring каждого экземпляра объекта Location.Я уже понимаю, что это то, что происходит, когда элемент, который вы пытаетесь привязать к отображаемому значению, не найден.
Я пролил это на несколько часов, и я не вижу, что может вызвать проблемы здесь.Я надеюсь, что кто-то может поделиться некоторым пониманием.