1

I was wondering how to go about calling a VOID method; located in my Default code behind, from a web user control?

The control contains a statement that needs to use the method that I have declared in my Default page code behind. I would just declare the method in the control's code behind but the method will be used multiple times so ideally, I would like to keep it in either the Default code behind or even put it in a class.

The problem is that I've tried keeping it in the Default's public partial class and I've attempted to create a separate class but I cant figure out how to call it when I need to use it.

The class from within Default.aspx.cs:

// This method adds a string to the status output area
public void AddStatusMessage(string type, string message)
{
    if (message == string.Empty || type == string.Empty) { return; }

    if (type == "success")
    {
        successMessageList.Add("SUCCESS: " + message);
        Session["SuccessMessageList"] = successMessageList;
    }
    else if (type == "error")
    {
        errorMessageList.Add(message);
        Session["ErrorMessageList"] = errorMessageList;
    }
}

The statement within a user control that needs to use the method:

// did the user enter a provider code but not check the confirmation box?
if (!ConfirmProviderCheckbox.Checked)
{
    failed = true;
    AddStatusMessage("error", "You must confirm the provider before proceeding.");
}

I would think calling the method like this from within the user control:

Namespace.Default.AddStatusMessage("error", "You must confirm the provider before proceeding.");

..but this does not seem to work.

Update 3/24: Well, I've tired to create an instance of that class within the static method to allow me to call it from my user control but I get Unknown method 'AddStatusMessage()' of Default. It's as if the new instance does not recognize my original method within the Default page class.

public static void PublicStatusMessage()
{
    Default Status = new Default().AddStatusMessage();
    Status.AddStatusMessage();
}
Cody Hicks
  • 420
  • 9
  • 24
  • 3
    There are many similar questions - look around... You either need to call static method OR create/get instance and call instance method on it. – Alexei Levenkov Mar 24 '14 at 02:54
  • I realize that there are other types of methods that can be made static to accomplish this but the method I'm trying to use doesn't return a value. :/ – Cody Hicks Mar 24 '14 at 02:55
  • And? being `static` or instance has nothing to do with return value... – Alexei Levenkov Mar 24 '14 at 02:59
  • @Alexei Levenkov I see where your coming from now. Since static is not an option in my case, I'll try to create an instance of the class and invoke the method on it. http://stackoverflow.com/questions/1360183/how-do-i-call-a-non-static-method-from-a-static-method-in-c – Cody Hicks Mar 24 '14 at 03:16

1 Answers1

1

If your method AddStatusMessage is static and located e.g. in your namespace called A and in the class called B, the correct way for calling it is: A.B.AddStatusMessage("some text", "some text");.

However to do so you need to declare your method (AddStatusMessage) as static. If the method is not static you need to create an instance of the class B (which is done by using A.B myB = new A.B(); and afterwards calling the method on this instance myB.AddStatusMessage("some text", "some text");.

If the class is in the same namespace like the calling class, you do not need to add the namespace prefix.

As already explained in some comments, static has nothing to do whether the method returns a value or not. Simply spoken the keyword static means that you can call this method directly by accessing via the class it is implemented in AND that within this method you have no access to instance members.

If I understood you correctly you want something like this:

public static void AddStatusMessage(string type, string message, System.Web.SessionState.HttpSessionState sessionState, List<string> successMessageList, List<string> errorMessageList)
{
    if (string.IsNullOrEmpty(message) || string.IsNullOrEmpty(type)) 
    {
        return; 
    }

    if (type == "success")
    {
        if (successMessageList != null)
        {
            successMessageList.Add("SUCCESS: " + message);
        }

        if (sessionState != null)
        {
            sessionState["SuccessMessageList"] = successMessageList;
        }
    }
    else if (type == "error")
    {
        if (errorMessageList != null)
        {
            errorMessageList.Add(message);
        }

        if (sessionState != null)
        {
            sessionState["ErrorMessageList"] = errorMessageList;
        }
    }
}

However there are some things you should think about: What happens if type is neither "success" nor "error". In cases like this it would be wise to use an enum. In this way it's no possible to get "unwanted" values. The next point is: Why are there two lists? Why can't you add both, success and error into one list? The list goes on and on...

Markus Safar
  • 6,324
  • 5
  • 28
  • 44
  • I suppose I was incorrect to say that it couldnt be made static because no value is returned. I think the issue I'm having is that when i try declaring `AddStatusMessage` a static method, intellisence tells me that `successMessageList` and `Session` cannot be referenced from a static context. I tried creating a new instance of my class as well but I get _Unknown method 'AddStatusMessage()' of Default_. Default class is a public partial class if that has anything to do with it. Thanks.. – Cody Hicks Mar 24 '14 at 21:11
  • 1
    That the class is `public partial` just means that it can be seen by anyone / from everywhere and partial means that it can be extended somewhere else. So the problem must be somewhere else. If you declare a method `static` you do not have access to instance members. So if you would make `successMessageList` static too you could access it. However you won't be able to change `Session`. I would suggest a change in your code. Where you call `AddStatusMessage` just pass Session and `successMessageList` as parameters too. Like `AddStatusMessage(string a, string b, SessionState s, List l)` – Markus Safar Mar 24 '14 at 21:27
  • ...Sorry for the stupid parameter names but I went out of characters. I hope you get the point? In the method you access by using s (where I would name it state) instead of `Session` and add the list by using l (which I would name list) instead of `successMessageList`. – Markus Safar Mar 24 '14 at 21:29
  • 1
    No worries, I see what you mean. I may have seen that used elsewhere in fact. I'll give that a try when I get a chance. I your thorough explanation. I'll get back to you and let you know how it works out. – Cody Hicks Mar 25 '14 at 02:30
  • The fact is, I'm re-building a website that was done by a previous developer. There is another method in the program that listens for a session value and if a value exists, the message is displayed on a page. I think that once the message is displayed, the sessions are cleared. I tried the code you've posted in your answer and can call the method from another class but I'm getting the "Unknown Method" error. I've done it like this...`Status.AddStatusMessage("error", "You must confirm the provider before proceeding.");` I may be missing a parameter or something. – Cody Hicks Mar 25 '14 at 20:48
  • By "Unkown Method" error you mean, that you get an compiler error, right? – Markus Safar Mar 26 '14 at 09:49
  • Well, intellisense. Unknown method 'AddStatusMessage(string, string)' of MyClass. Although it clearly recognizes the method name from the class I am calling it from. It only underlines the parameters so I wonder if this is the issue. – Cody Hicks Mar 26 '14 at 12:53
  • I bet you have a type mismatch or missed some parameters but usually you should get a more readable error message like: _The best overloaded method match for '...' has some invalid arguments._ If you have used the method like I have provided it you need to specify 3 additional parameters: `Session`, `successMessageList` and `errorMessageList`. – Markus Safar Mar 26 '14 at 14:47
  • 1
    Ok. I think that was my issue..not specifying the additional parameters. – Cody Hicks Mar 26 '14 at 17:02
  • If it work's for you please vote the answer and mark it as correct. Thanks ;-) – Markus Safar Mar 26 '14 at 17:29
  • 1
    Gotcha. I haven't had a chance to check it out yet but I'll go with it. It seems promising. I appreciate your input. – Cody Hicks Mar 26 '14 at 17:47
  • One more question, how would I call the method after the method has been converted to how you have it? How would I specify the additional parameters? `Status.AddStatusMessage("error", "You must confirm the provider before proceeding.", ?, ?, ?); ` – Cody Hicks Mar 26 '14 at 19:55
  • By passing the 3 additional variables I have mentioned above. `Session`, `successMessageList` and `errorMessageList` – Markus Safar Mar 26 '14 at 20:12
  • I suppose I would define both error and success lists like this.. `List successMessageList = (List)Session["SuccessMessageList"]; List errorMessageList = (List)Session["ErrorMessageList"];` and then call my method like...`Status.AddStatusMessage("error", "You must confirm the provider before proceeding.", Session, successMessageList, errorMessageList);` . – Cody Hicks Mar 26 '14 at 20:15
  • 1
    Fantastic. I defined the 2 lists on the same page that I am calling from. That should do the trick. I'll find out later once I compile. It may be a few days though. – Cody Hicks Mar 26 '14 at 21:07