Alika87
Alika87

Reputation: 311

C#: Communication between main-class and winforms-class. Cannot pass over the data

I got a little question that causes me some problems, I am sure its not difficult, but for me right now it is.

I got two classes, one main-class and the class of my 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);
     }
    }

Here I get the values and try to write them into an Datagrid, via this method:

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

But the compiler tells me, that AddAttributeValue is not in the current context and I cannot call it. I got the values I want, but cannot pass them over to the form. I know it sounds trivial, but I just can't get it.

Upvotes: 1

Views: 187

Answers (2)

Deleted
Deleted

Reputation: 930

Make 'AddAttributeValue' public:

public void AddAttributeValue(string attribute, string value)

Addendum:

As per my comment below, here's how you'd implement a callback, to allow your main-class to call a method within your winform when it doesn't otherwise have an instance member to refer to:

Your MainClass will look something like this:

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

then in your Winform class, you'd call the method like so:

MainClass.DoStuff(this.AddAttributeValue);

That'll mean that when 'DoStuff' completes, the method called 'AddAttributeValue' gets called.

Upvotes: 1

bateloche
bateloche

Reputation: 709

If I did understood, the code snippets provided are in diferent classes.

In this case the method should be public.

Like that:

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

Upvotes: 1

Related Questions