How to use the same method with two different forms?

末鹿安然 提交于 2019-12-11 11:03:39

问题


To clarify: I have two forms that use the same method in my Controller, and I was wondering how to use the same lines of code rather than copying and pasting the method and using a different parameter for each method.

Eg. What I have now:

public static void PopulateOriginCombo(CableID_QueryView QView)
{
    if (QView.cmbAreaCode.Text != "")
    {
       //Code...
    }
}

public static void PopulateOriginCombo(CableID_CreateView CView)
{
    if (CView.cmbAreaCode.Text != "")
    {
       //Code...
    }
}

Can I combine the parameters of each form into one somehow?


回答1:


Since you want to avoid inheritance, create an interface:

interface IHasOriginCombo
{
    ComboBox cmbAreaCode { get; }
}

then, in your class declarations, add the interface:

class CableID_QueryView : Form, IHasOriginCombo { //...

class CableID_CreateView : Form, IHasOriginCombo { //...

then:

public static void PopulateOriginCombo(IHasOriginCombo view)
{
    if (view.cmbAreaCode.Text != "")
    {
       //Code...
    }
}



回答2:


You don't need to use inheritance to do this. Create another class which contains your methods and returns list of objects, then use it on different forms.

public class Origin
{
    public string originName { get; set; }

    public static List<Origin> PopulateOriginCombo(CableID_QueryView QView)
    {
        if (QView.cmbAreaCode.Text != "")
        {
           //Code...
        }
    }

    public static List<Origin> PopulateOriginCombo(CableID_CreateView CView)
    {
        if (CView.cmbAreaCode.Text != "")
        {
           //Code...
        }
    }
}

Then in your form, call it like this:

combo1.DataSource = Origin.PopulateOriginCombo(test);
combo1.DisplayMember = "originName";

Using objects is hard at first, but eventually you will find it easier to manipulate.




回答3:


how about create class that has this method than you can call this method :

public static string PopulateOriginCombo(CableID_CreateView CView)
{
   if(CView != null)
   {
       if (CView.cmbAreaCode.Text != "")
      {
         return CView.Text ;
      }
  }

  return string.Empty;
}

than just create object from that class and call this method and pass the CView to it like that :

SomeClass classObject = new SomeClass();
string value = classObject.PopulateOriginCombo(this.CView);


来源:https://stackoverflow.com/questions/25394337/how-to-use-the-same-method-with-two-different-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!