访问方法c#winforms时,对象引用未设置为对象的实例

时间:2014-02-24 05:04:02

标签: c# winforms

我想访问从Form2到Form1的InitializeWithFile方法.Form1是我的起始形式。

在FORM1中:

Form2 f2;

public Form1(Form2 _f2)
{
    f2 = _f2;
    StringA = @"D://abc.csv";
    InitializeComponent();
    string s = textBox1.Text;
    try
    {
        csvData = GetDataTabletFromCSVFile(StringA);
        dataGridView1.DataSource = csvData;
        //var f = new Form2();
        _f2.InitializeWithFile(StringA);
    }
    catch(Exception e)
    {
        MessageBox.Show(e.Message);
    }
    return;
}

public Form1()
    : this(null)
{

}

在FORM2中:

public void InitializeWithFile(string csFileName)
{
    StreamReader hGetCommaDelimiterGrid = new StreamReader(csFileName);

    m_arycsFullData.Clear();
    m_arycsFilteredData.Clear();

    m_arycsLogsExcluded.Clear();
    m_arycsLogsIncluded.Clear();

    m_arycsSidesExcluded.Clear();
    m_arycsSidesIncluded.Clear();

    m_arycsMainCodesExcluded.Clear();
    m_arycsMainCodesIncluded.Clear();
    m_arycsMinorCodesExcluded.Clear();
    m_arycsMinorCodesIncluded.Clear();

    while (bReadingFile)
    {
        bReadingFile = Convert.ToBoolean(hGetCommaDelimiterGrid.ReadToEnd());
        if (bReadingFile)
        {
            csCell = GetFilteredData(iRow, SORT_COLUMN_LOG);

            //AddOptionsText(SORT_INDEX_LOG,csCell);
            AddIncludedText(SORT_INDEX_LOG, csCell, true);

            csCell = GetFilteredData(iRow, SORT_COLUMN_SIDE);
            //AddOptionsText(SORT_INDEX_SIDE,csCell);
            AddIncludedText(SORT_INDEX_SIDE, csCell, true);

            csCell = GetFilteredData(iRow, SORT_COLUMN_MAIN_CODE);
            //AddOptionsText(SORT_INDEX_MAIN_CODE,csCell);
            AddIncludedText(SORT_INDEX_MAIN_CODE, csCell, true);

            csCell = GetFilteredData(iRow, SORT_COLUMN_MINOR_CODE);
            //AddOptionsText(SORT_INDEX_MINOR_CODE,csCell);
            AddIncludedText(SORT_INDEX_MINOR_CODE, csCell, true);
        }
        iRow++;
    }
    }

CSMSioFile相当于c#??????

2 个答案:

答案 0 :(得分:0)

您可以尝试在Form2的构造函数中传递Form1实例

答案 1 :(得分:0)

不允许在Form1中将Form2作为参数传递。

您的错误发生是因为在执行程序时加载Form1时Form2甚至没有初始化。

所以解决这个问题的方法是你可以在Form1中创建Form2的对象,如下所示:

Form2 frm2 = new Form2();
frm2.InitializeWithFile(StringA);

或者在Form2中创建静态方法:

public static void InitializeWithFile(string csFileName){//Your Code code}

并在::

下使用它
Form2.InitializeWithFile(StringA);