【问题标题】:Sending an Array to Controls向控件发送数组
【发布时间】:2019-12-03 15:44:50
【问题描述】:

所以,我是一名开始在学校学习 C# 的学生,我目前的一个项目涉及将可扩展的类方法绑定数组输出到表单上的控件,我遇到了一个令人困惑的问题。我已经将适当的访问修饰符设置为 public,我之前已经成功地将这种格式用于可扩展数组,并且我的程序没有显示构建错误,但数据不会输出。

我可以看到我的逻辑错误是我的数组声明的一部分,在过去的排列中它似乎没有扩展,尽管我当前的策略调用了 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;
}

outputtextOutput 都是方法输入,textOutput 被声明为 int,以便它可以用作对数组放置的直接引用。

【问题讨论】:

  • 您没有将项目添加到列表框中,您只是添加了索引i。如果Noob 类覆盖ToString(),您可以使用report.newStudentSelectionBox.DataSource = info; 直接显示数组项而无需循环。或者无需通过设置DisplayMemberValueMember 属性来覆盖ToString()。这个神秘的方法Expand是做什么的?调试看看会发生什么。 Tutorial: Learn to debug C# code using Visual Studio.
  • 不确定Expand() 是做什么的,但您只是将 i 变量添加到该列表框中,该变量将是一个整数。假设 noob.index 已经是一个整数(最好是整数,否则在解析它的字符串表示时会抛出异常),则无需将其转换为字符串然后再转换回 int。除非作业特别说明您需要在代码中手动添加值,否则您应该查看数据绑定。
  • 如果手动绑定是必需的,则为您的Noob 类覆盖ToString 方法并返回您希望在ListBox 中显示的属性,然后只需添加Noob 实例直接指向ListBoxItems 集合。

标签: c# arrays controls output


【解决方案1】:

试试这个

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);
}

【讨论】:

    猜你喜欢
    • 2022-10-18
    • 1970-01-01
    • 2020-05-10
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    • 2018-11-16
    • 2017-07-31
    相关资源
    最近更新 更多