【问题标题】:How to get list<string> value using foreach in another form in c#?如何在 c# 中以另一种形式使用 foreach 获取 list<string> 值?
【发布时间】:2018-01-24 22:42:00
【问题描述】:

我想使用 foreach 循环以另一种形式获取 List&lt;string&gt;

ReportTestForm.cs

private void ReportTestForm_Load(object sender, EventArgs e)
{
    List<string> fieldList = new List<string>();

    fieldList.Add("Name");
    fieldList.Add("Class");
    fieldList.Add("Address");
    fieldList.Add("City");

    ReportFilterForm report = new ReportFilterForm(fieldList);
    report.Show(this);
}

ReportFilterForm.cs

public ReportFilterForm(List<string> fieldListFromReport)
{
    List<string> record = new List<string>(fieldListFromReport);
    foreach(string fields in record)
    {
        listBoxFieldNames.Items.Add(fields);
    }
}

它抛出异常称为空引用异常

【问题讨论】:

    标签: c# arrays winforms list collections


    【解决方案1】:

    看起来您在调用负责实例化控件的 InitializeComponent() 方法之前访问控件,因此在此之前访问控件当然会导致 NRE (Null Reference Exception),请确保您首先调用它,对此有多种可能的解决方案。以下是那些:

    解决方案 1:

    在访问构造函数中的控件之前调用InitializeComponent()

    public ReportFilterForm(List<string> fieldListFromReport)
    {
        InitializeComponent(); // note this
        List<string> record = new List<string>(fieldListFromReport);
    
        foreach(string fields in record)
        {
            listBoxFieldNames.Items.Add(fields);
        }
    
    }
    

    解决方案 2:

    您可以使用this() 调用无参数构造函数,因为通常该构造函数包含对InitializeComponent 方法的调用:

    public ReportFilterForm(List<string> fieldListFromReport) 
             : this() // call parameterless constructor
    {
    
        List<string> record = new List<string>(fieldListFromReport);
    
        foreach(string fields in record)
        {
            listBoxFieldNames.Items.Add(fields);
        }
    
    }
    

    解决方案 3:

    您可以在 FormLoad 事件中访问它,就像您在调用它的代码 sn-p 中所做的那样:

    public class ReportFilterForm
    {
        List<string> _record;
        public ReportFilterForm(List<string> fieldListFromReport)
             : this()
        {
            _record = new List<string>(fieldListFromReport);
        }
    
        public ReportFilterForm()
        {
             InitializeComponent(); 
        }
    
        public void ReportFilterForm_Load(object sender, EventArgs e)
        {
    
          foreach(string fields in _record)
          {
             listBoxFieldNames.Items.Add(fields);
          }
       }
    
    }
    

    【讨论】:

    • 正确的兄弟。谢谢。我会在 10 分钟后接受你的回答。
    • 很高兴为您提供帮助 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多