2012-07-16 88 views
0

我有3種形式,他們每個都有自己的網格。下面的代碼當前寫在form1上,但被所有3種形式使用。它的工作原理非常混亂而且很長,因爲它必須適用於3種使用不同數據庫幷包含不同列的表單。將下面的代碼拆分成3個獨立的函數並放在每個表單的背面,只包含該特定表單所需的數據會被認爲是更合適的嗎?這種情況下的代碼組織和可重用性?

Public Class Form1 

Public sFilter as string 
Public sQuery as string 


Public Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load  

Public Sub buildFilter(ByVal form as string) 
    select case form 
    Case "form1" 
    sFilter = "control_no > 0 and control_no < 10000" 
    Case "form2" 
    sFilter = "quantity > 0 and quantity < 7849" 
    Case "form3" 
    sFilter = "store_id > 10000" 
    end select 
End Sub 

Public Sub buildQuery(form) 
    Select case form 
    Case "form1" 
    sQuery = "Select * FROM dataBase1 WHERE " & sFilter 
    Case "form2" 
    sQuery = "Select quantity, first_name, last_name FROM database2 WHERE " & sFilter 
    Case "form3" 
    sQuery = "Select * FROM dataBase3 WHERE " & sFilter 
    End Select 
End Sub 


End Class 

有人告訴我,這將是最好採取上面的代碼並將其放置在每一個表格的背面,只有有這樣的形式:其上工作。我覺得這不是最好的方法,但我也覺得它目前的設置方式也不好。什麼是一個好方法?

回答

1

建造這些方法爲一種常見的遺傳形式,然後通過你的其他形式的繼承它:

Public MustInherit Class MyInheritedForm 
    Inherits System.Windows.Forms.Form 

    Public sFilter as string 
    Public sQuery as string 


    Public Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load  

    Public Sub buildFilter(ByVal form as string) 
     select case form 
     Case "form1" 
     sFilter = "control_no > 0 and control_no < 10000" 
     Case "form2" 
     sFilter = "quantity > 0 and quantity < 7849" 
     Case "form3" 
     sFilter = "store_id > 10000" 
     end select 
    End Sub 

    Public Sub buildQuery(form) 
     Select case form 
     Case "form1" 
     sQuery = "Select * FROM dataBase1 WHERE " & sFilter 
     Case "form2" 
     sQuery = "Select quantity, first_name, last_name FROM database2 WHERE " & sFilter 
     Case "form3" 
     sQuery = "Select * FROM dataBase3 WHERE " & sFilter 
     End Select 
    End Sub 


End Class 

然後你只需要:

Public Class Form1 
    Inherits MyInheritedForm 


End Class 

而你的方法和繼承一起出現。

+0

Ahh謝謝喬爾,這正是我一直在尋找的。並在第8行 「公共form1_load」是否應該是「Public MyInheritedForm_load」? – Garrettchap1 2012-07-16 15:45:13

+0

@ Garrettchap1:只要你有'Handles Me.Load',就可以稱之爲無所謂。 – 2012-07-16 15:48:18

1

將三種形式的所有代碼都沒有意義。

一種選擇是使用一個窗體與您已有的代碼並根據您使用的連接設置窗體的屬性。

如果這三種形式在設計上有所不同,並連接到不同的數據庫,那麼爲什麼不只是有三種不同的形式,並且有三組不同的查詢和過濾代碼?

旁註:你也應該看看parametrised queries