2013-07-18 17 views
1

我得到了一个小问题,导致我出现了一些问题,我相信它并不难,但对我来说现在就是这样。C#:主类和winforms类之间的通信。无法通过数据

我有两个班,一个主班和我的winform班。

foreach (EA.Element theElement in myPackage.Elements) 
    { 
    foreach (EA.Attribute theAttribute in theElement.Attributes) 
    { 
    attribute = theAttribute.Name.ToString(); 
    value = theAttribute.Default.ToString(); 
    AddAttributeValue(attribute, value); 
    } 
    } 

这里我得到的值,并尝试将其写入到一个Datagrid的,通过这种方法:

private void AddAttributeValue(string attribute, string value) 
    { 
     int n = dataGridView1.Rows.Add(); 
     dataGridView1.Rows[n].Cells[0].Value = attribute; 
     dataGridView1.Rows[n].Cells[1].Value = value; 
    } 

但是,编译器告诉我,那AddAttributeValue是不是在目前情况下,我不能打电话它。我得到了我想要的值,但无法将它们传递给表单。我知道这听起来微不足道,但我无法得到它。

+1

标准OOP的问题,您需要将表格对象的引用。并公开该方法。 –

+0

我在开始的时候公开过它,那不是问题,也不是解决方案,它肯定是不同的东西,但无论如何谢谢。 – Alika87

+0

明白了,谢谢:) – Alika87

回答

1

使“AddAttributeValue”市民:

public void AddAttributeValue(string attribute, string value) 

附录:

按我下面的评论,这里是你如何实现回调,让你的主类中调用一个方法,你WinForm的时候它不以其他方式有一个实例成员是指:

你MainClass会是这个样子:

public static class MainClass 
{ 
    public delegate void AddAttributeValueDelegate(string attribute, string value); 

    public static void DoStuff(AddAttributeValueDelegate callback) 
    { 
     //Your Code here, e.g. ... 

     string attribute = "", value = ""; 

     //foreach (EA.Element theElement in myPackage.Elements) 
     //{ 
     // foreach (EA.Attribute theAttribute in theElement.Attributes) 
     // { 
     //  attribute = theAttribute.Name.ToString(); 
     //  value = theAttribute.Default.ToString(); 
     //  AddAttributeValue(attribute, value); 
     // } 
     //} 
     // 
     // etc... 
     callback(attribute, value); 
    } 
} 

然后在WinForm的类,你会打电话像这样的方法:

MainClass.DoStuff(this.AddAttributeValue); 

那将意味着,当“DoStuff”完成,称为“AddAttributeValue”的方法被调用。

+0

谢谢,但那不是解决办法,我也在公开场合。问题是别的。 – Alika87

+1

再看看你的代码,看起来你试图在另一个类中调用一个实例成员,但是你没有要引用的实例。您的代码正在您的主类中寻找名为“AddAttributeValue”的方法。你需要获取你的winform的一个实例,并引用*它的'AddAttributeValue'实现,或者创建AddAttributeValue静态并通过MyWinformClass.AddAttributeValue引用它。 (注意:如果你做了第二个,那么访问winform类的特定于实例的成员可能会遇到一些问题,比如你的'dataGridView1'成员)。 – Deleted

+0

我推荐的是将回调传递给你的主类。我会在一分钟内提供另一个答案,证明这个想法在工作中。 – Deleted

1

如果我明白了,所提供的代码片段有不同的类。

在这种情况下,该方法应该是公开的。

就像是:

public void AddAttributeValue(string attribute, string value) 
{ 
    int n = dataGridView1.Rows.Add(); 
    dataGridView1.Rows[n].Cells[0].Value = attribute; 
    dataGridView1.Rows[n].Cells[1].Value = value; 
}