【发布时间】:2013-12-20 12:17:25
【问题描述】:
我看了又看,但似乎找不到任何解决此问题的方法,所以我决定还是问问。
我正在关注this tutorial,以帮助我使用 WinForms 在 C# 中创建地址簿。我已经创建了 GUI,以及将它们组合在一起的“Person”类,我可以添加条目就好了。但是当我编写代码以在它们之间切换时,按照教程中的内容,我收到以下错误消息:
“object”不包含“Index”的定义,并且找不到接受“object”类型的第一个参数的扩展方法“Index”(您是否缺少 using 指令或程序集引用?)
这是我的“SelectedIndexChanged”事件代码。它与教程略有不同:我将“entryList.SelectedItems[0].Index”放入预定义的 int“i”中以节省写出八次,我的 GUI 相当不同,我定义了列表由于各种原因,Person 对象位于单独的“方法”类中。不过基本原理是一样的,所以我不明白为什么我的会报错而他的不会。
private void entryList_SelectedIndexChanged(object sender, EventArgs e)
{ //set the text boxes to display the data in the selected entry
if (entryList.SelectedItems.Count > 0)
{
i = entryList.SelectedItems[0].Index;
nameText.Text = Methods.list[i].Name;
birthDay.Text = Methods.list[i].BirthDay.ToString();
birthMonth.Text = Methods.list[i].BirthMonth.ToString();
birthYear.Text = Methods.list[i].BirthYear.ToString();
numberText1.Text = Methods.list[i].NumberPart1;
numberText2.Text = Methods.list[i].NumberPart2;
addressText.Text = Methods.list[i].Address;
eMailText.Text = Methods.list[i].Email;
}
}
标记错误的是“.Index”部分,我不知道为什么。那么,我哪里做错了?
编辑:为了澄清,我尝试了各种解决方法,例如
i = entryList.SelectedIndex;
但那些仍然不允许我在 ListBox 中的项目之间切换,它会一直显示我输入的最后一个项目。
编辑 2:Rotem 要求的更多信息。这是添加条目的代码,这会将其添加到 Person 对象列表中,该列表出于各种原因保存在单独的 Methods 类中(因此是 Methods.list)。它还将人名添加到 ListBox 列表中,理论上,我希望能够通过单击 ListBox 中的名称在查看不同条目之间切换,这就是第一个代码段的用途。除非那行不通。
private void newEntry_Click(object sender, EventArgs e)
{ //creates a new entry, displaying its data in the appropriate fields, and then saves it
Person p = new Person(nameText.Text, Convert.ToByte(birthDay.Text), Convert.ToByte(birthMonth.Text), Convert.ToInt16(birthYear.Text), numberText1.Text, numberText2.Text, addressText.Text, eMailText.Text);
Methods.list.Add(p);
entryList.Items.Add(p.Name);
nameText.Text = " ";
birthDay.Text = "DD";
birthMonth.Text = "MM";
birthYear.Text = "YYYY";
numberText1.Text = " ";
numberText2.Text = " ";
addressText.Text = " ";
eMailText.Text = " ";
}
编辑 3:根据要求,这是“Person”类的代码:
class Person
{
private static string name;
private static byte birthDay;
private static byte birthMonth;
private static short birthYear;
private static string numberPart1;
private static string numberPart2;
private static string address;
private static string email;
//encapsulation goes here...
public Person(string a, byte b, byte c, short d, string e, string f, string g, string h)
{
name = a;
if (b <= 31 && c <= 12 && d < DateTime.Now.Year)
{
birthDay = b;
birthMonth = c;
birthYear = d;
}
else
throw new ArgumentException("Invalid date of birth");
numberPart1 = e;
numberPart2 = f;
address = g;
email = h;
}
}
【问题讨论】:
标签: c# winforms user-interface selectedindexchanged