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

有人告诉我,最好将上面的代码放在每个表格的背面,并且只让它与它所在的表格一起工作。我觉得这不是最好的方法,但我也觉得它目前的设置方式也不好。什么是好方法?

4

2 回答 2

1

以三种形式拥有所有这些代码是没有意义的。

一种选择是将一个表单与您已有的代码一起使用,并根据您使用的连接设置表单的属性。

如果这三种表单的设计不同并且连接到不同的数据库,那么为什么不使用三种不同的表单以及三组不同的查询和过滤代码呢?

旁注:您还应该查看参数化查询

于 2012-07-16T15:33:29.000 回答
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

而且您的方法与继承一起出现。

于 2012-07-16T15:36:29.387 回答