2016-02-27 12 views
2

我有3種形式,即Form1,Form2 & Form3如何檢查使用哪種表單來訪問當前表單?

Form1Form2都能夠訪問Form3。但是,我打算給不同的功能一個按鈕在Form3取決於哪種形式用於訪問Form3

有沒有人可以向我解釋如何編碼應該工作?此外,如果你們有鏈接,這個問題以前的答案或更好的概念,我會高度讚賞它。提前致謝。

我粗略的想法

Public Class Form3 
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
     If 'user are access from Form1 Then 
      'Action if user are access from Form1 here 
     Else 
      'Action if user are access from Form2 here 
     End If 
    End Sub 
End Class 

回答

2

該代碼的問題

If Me.Owner.Equals(Form1) Then . . . 

這種方式,你有緊密耦合的對象 - Form2和1知道Form3和Form3知道2和1.它可能不是你或現在的問題。但是在OOP中這是一個問題,將來它可能會成爲您的對象可擴展性的問題。這是面向對象的方法。從我的頭寫,所以有可能是語法不正確項:

Public Interface IFormCanDoSomething 
    Sub DoSomething() 
    ReadOnly Property FormAction As EnumFormActions 
End Interface 

Public Class Form1 
    Implements IFormCanDoSomething 

    ReadOnly Property FormAction As EnumFormActions Implements IFormCanDoSomething.FormAction 
     Get 
      Return EnumFormActions.Action1 
     End Get 
    End Property 

    Sub DoSomething() Implements IFormCanDoSomething.DoSomething 
     Dim f As New Form3(Me) 
     f.Show() 
    End Sub 
End Class 

Public Class Form2 
    Implements IFormCanDoSomething 

    ReadOnly Property FormAction As EnumFormActions Implements IFormCanDoSomething.FormAction 
     Get 
      Return EnumFormActions.Action2 
     End Get 
    End Property 

    Sub DoSomething() Implements IFormCanDoSomething.DoSomething 
     Dim f As New Form3(Me) 
     f.Show() 
    End Sub 
End Class 


Public Class Form3 

    Private _owner As IFormCanDoSomething 
    Public Sub New(owner As IFormCanDoSomething) 
     _owner = owner 
    End Sub 

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
     If _owner.FormAction = EnumFormActions.Action1 Then 
      'Action if user needs one thing 
     ElseIf _owner.FormAction = EnumFormActions.Action2 Then 
      'Action if user needs another thing here 
     ElseIf _owner.FormAction = EnumFormActions.Action3 Then 
      'Action if user needs third thing 
     End If 

    End Sub 
End Class 

那麼,什麼是這裏的收穫?看看Button1_Click。你有看到? - 現在你可以有多種形式,其中Form3需要執行Action1,或/和許多形式,Form3需要執行Action2等。這可以走得更遠,但現在足夠好

+0

感謝您的幫助,真正有用的答案!將嘗試一下並回饋給你。 – Gideon

1

假設你正在使用Show方法,通過形式爲業主進去:

Form3.Show(Form1) 

然後引用Form3業主:

Public Class Form3 
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    If Me.Owner.Equals(Form1) Then 
      'Action if user are access from Form1 here 
    ElseIf Me.Owner.Equals(Form2) Then 
      'Action if user are access from Form2 here 
    End If 
    End Sub 
End Class 
+0

感謝您的幫助,感謝它!問題解決了。 – Gideon

+0

是Else Me.Owner.Equals(Form2)那麼'應該是'ElseIf Me.Owner.Equals(Form2)Then'?即其他**如果**? – aneroid

+0

@aneroid是的,它應該是'ElseIf Me.Owner.Equals(Form2)Then' – Gideon