Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

Define name of winForm that using the class? C#

I am developing a project with 20 winforms in C#. These forms uses comman class named "databaseOperations". My question is how can i define the winform name(sender) that using method in this class. I want to do something like that below;

public class databaseOperations
    {
        public void loadfile(string path)
        {
            //if (sender form.name== "FormA")
                 {// codes...........;}
            //else if (sender form.name== "FormB")
                 {// codes...........;}
            
        }
    }

I want to get name of winform.

Thanx in advance,

question from:https://stackoverflow.com/questions/65942371/define-name-of-winform-that-using-the-class-c-sharp

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A standard pattern is to define this method:

public void LoadFile(Form sender, string path)

Which we call like that:

var dbOps = new DatabaseOperations();

dbOps.LoadFile(myForm or this, "pathToFile");

Thus now we can check like that:

if ( sender.Name == "SomeName" )
{ 
  //...
} 

Or anything else from the sender instance like for example:

sender.Tag

typeof(sender)

This last allows to make a difference between:

  • MyFormA
  • MyFormB
  • And so on...
var typeSender = sender.GetType();
if ( typeSender == typeof(MyFormA) )
else
if ( typeSender == typeof(MyFormB) )

Also a switch can be used.

Instead of using a string name, so if is more robust and maintainable as strings can easily be change and we need to propagate that by hand, and this may cause big problems. Using types, refactoring tools do that for us.

But if several instances of MyForm can have differents Name property values, so we can check it, that's fine too, that just needs to take care.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...