C# 向控件发送数组
因此,我是一个在学校开始学习C#的学生,我目前的一个项目涉及到将可扩展的、类方法绑定的数组输出到表单上的控件,我遇到了一个令人困惑的障碍。我已经将正确的访问修饰符设置为public,我以前成功地将此格式用于可扩展数组,并且我的程序没有显示生成错误,但数据不会输出 我可以看到我的逻辑错误是我数组声明的一部分,在过去的排列中它似乎没有扩展,尽管我当前的策略调用了C# 向控件发送数组,c#,arrays,controls,output,C#,Arrays,Controls,Output,因此,我是一个在学校开始学习C#的学生,我目前的一个项目涉及到将可扩展的、类方法绑定的数组输出到表单上的控件,我遇到了一个令人困惑的障碍。我已经将正确的访问修饰符设置为public,我以前成功地将此格式用于可扩展数组,并且我的程序没有显示生成错误,但数据不会输出 我可以看到我的逻辑错误是我数组声明的一部分,在过去的排列中它似乎没有扩展,尽管我当前的策略调用了Expand()方法,直接增加了我的索引noobIdentifier,它是类内的通用变量,而不是实际的方法 //Create Form In
Expand()
方法,直接增加了我的索引noobIdentifier
,它是类内的通用变量,而不是实际的方法
//Create Form Instance
AttendanceReport report = new AttendanceReport();
//Expand Array
Expand();
//Create Array
int SIZE = noobIdentifier + 1;
Noob[] info = new Noob[SIZE];
//Assign Data to Array
info[noobIdentifier].s_class = Class;
info[noobIdentifier].s_name = Name;
info[noobIdentifier].s_id = ID;
info[noobIdentifier].s_password = Password;
info[noobIdentifier].s_formerDistrict = District;
info[noobIdentifier].s_grade = Grade;
info[noobIdentifier].s_country = Country;
info[noobIdentifier].index = SIZE;
它也可以是我的实际输出块的一部分。我曾考虑在Listbox输出中尝试使用For循环而不是Foreach,尽管后者似乎更简洁
//Ouput Gateway
if (output == true)
{
//Temp Holder
int i;
//Output items to Attendance Report Listbox
foreach (Noob noob in info)
{
//Send Index to string
string indexer = noob.index.ToString();
//Convert to Int
i = int.Parse(indexer);
report.newStudentSelectionBox.Items.Add(i);
}
}
//Output Text Gateway
if (textOutput > 0)
{
//Declare Index
int n = textOutput - 1;
report.classOutput.Text = info[n].s_class;
report.nameOutput.Text = info[n].s_name;
report.idOutput.Text = info[n].s_id.ToString();
report.gradeOutput.Text = info[n].s_grade.ToString();
report.districtOutput.Text = info[n].s_formerDistrict;
report.countryOutput.Text = info[n].s_country;
}
output
和textOutput
都是方法输入,其中textOutput
被声明为int
,因此它可以用作数组放置的直接引用。尝试一下
在Noob
类中:
public class Noob
{
//Your Definition...
public override string ToString() => this.Name;
}
修改循环类型:
//Output items to Attendance Report Listbox
foreach (Noob noob in info)
{
report.newStudentSelectionBox.Items.Add(noob);
}
您没有将项目添加到列表框,您只是添加索引
i
。如果Noob
类重写了ToString()
,则可以直接显示数组项,而不使用以下循环:report.newStudentSelectionBox.DataSource=info代码>。或者不需要通过设置DisplayMember
和ValueMember
属性来覆盖ToString()
。这个神秘的方法扩展
做什么?调试以查看发生了什么。不确定Expand()
的作用是什么,但您只添加了i变量,它将是列表框中的整数。假设noob.index
已经是一个整数(最好是整数,否则在解析它的字符串表示时会抛出异常),那么就不需要将其转换为字符串,然后再转换回int。除非赋值特别说明需要在代码中手动添加值,否则您应该查看数据绑定。如果需要手动绑定,然后为Noob
类重写ToString
方法,返回希望在ListBox
中显示的属性,然后直接将Noob
实例添加到ListBox
的项集合中。