2013年4月28日 星期日

[技巧] 設置 DataGridViewComboBoxCell / ComboBox DropDownWidth 下拉式選項的寬度

需求:
設置來源資料中最大長度的字串為寬度

程式(VB):
 Dim graphics = CreateGraphics()

columnSex.DropDownWidth = _
     (From width In (From item As DataRow In dt供應商.Rows _
     Select Convert.ToInt32(graphics.MeasureString(item("供應商簡稱").ToString, Font).Width)) _
     Select width).Max

2013年4月26日 星期五

[技巧] DataGridView 驗證欄位的資料型態 以及 是否空白

程式:

    Private Sub DataGridView1_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit

        'DataGridView1.Rows(e.RowIndex).ErrorText = String.Empty
    End Sub

Private Sub DataGridView1_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating

        If e.ColumnIndex >= 10 AndAlso e.ColumnIndex <= 19 Then
            Exit Sub
        End If

        Dim newInteger As Integer
        Dim newDeciaml As Decimal

        Dim grid As DataGridView = CType(sender, DataGridView)
        grid.Rows(e.RowIndex).ErrorText = ""

        If String.IsNullOrEmpty(e.FormattedValue.ToString) Then
            DataGridView1.Rows(e.RowIndex).ErrorText = _
            "不允許空白!!"
            MsgBox("不允許空白")
            e.Cancel = True
        Else If grid.Columns(e.ColumnIndex).Name = "新增次數" OrElse grid.Columns(e.ColumnIndex).Name = "序號" _

           OrElse grid.Columns(e.ColumnIndex).Name = "項次" Then
            If Not Integer.TryParse(e.FormattedValue.ToString(), newInteger) _
                OrElse newInteger < 0 Then
                DataGridView1.Rows(e.RowIndex).ErrorText = _
                "只允許Integer!!"
                MsgBox("只允許Integer")
                e.Cancel = True
            End If
        ElseIf grid.Columns(e.ColumnIndex).Name = "金額" Then
            If Not Decimal.TryParse(e.FormattedValue.ToString(), newDeciaml) Then
                DataGridView1.Rows(e.RowIndex).ErrorText = _
                "只允許Decimal!!"
                MsgBox("只允許Decimal")
                e.Cancel = True
            End If
        End If

    End Sub

參考:
DataGridView: why is CellValidating firing as the grid is filling?
DataGridView.CellValidating 事件,確定使用者只輸入正整數。
DataGridView中数据输入验证
c# DataGridView中的单元格中只能输入数字的解决方法
C#如何在DataGridView控件中验证数据输入
DataGridViews, DataBinding and non validating cell values
[C#]DataGridView欄位驗證只能是數字且不能為空白
WinForm中DataGridView验证单元格输入的是数字
[ADO.NET][WinForm] 限制 DataGridView 輸入字元
DataGridView 控制項 (Windows Form)

判斷是否為數字、整數的正則表達式方法
C#检测字符串是否为正整数

[技巧] DataGridViewComboBoxColumn 實現 SelectedIndexChanged 事件

程式:
Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing

        'If Me.DataGridView1.CurrentCell.OwningColumn.Name = "供應商別" Then
                       Dim comboBox1 As ComboBox = CType(e.Control, ComboBox)
            AddHandler comboBox1.SelectedIndexChanged, _
                New EventHandler(AddressOf ComboBox_SelectedIndexChanged)
        'End If
End Sub

Private Sub ComboBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        'do something here
         Dim comboBox1 As ComboBox = CType(sender, ComboBox)
         MsgBox(comboBox1.SelectedValue.ToString)
End Sub

DEBUG:
上面的寫法會引發多次觸發,甚至出現 「並未將物件參考設定為物件的執行個體」錯誤。
如果沒有 If Me.DataGridView1.CurrentCell.OwningColumn.Name = "供應商" Then 
則會造成 DGV 上所有的 DataGridViewComboBoxColumn 都可註冊事件。
因此便需更改如下!

Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
     
        If Me.DataGridView1.CurrentCell.OwningColumn.Name = "供應商" Then
            Dim comboBox1 As ComboBox = CType(e.Control, ComboBox)
            If (comboBox1 IsNot Nothing) Then
                ' Remove an existing event-handler, if present, to avoid
                ' adding multiple handlers when the editing control is reused.
                RemoveHandler comboBox1.SelectedIndexChanged, New EventHandler(AddressOf ComboBox_SelectedIndexChanged)

                ' Add the event handler.
                AddHandler comboBox1.SelectedIndexChanged, New EventHandler(AddressOf ComboBox_SelectedIndexChanged)
            End If
        End If

End Sub


Private Sub ComboBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim comboBox1 As ComboBox = CType(sender, ComboBox)
        If CType(sender, ComboBox).SelectedValue IsNot Nothing Then
            MsgBox(comboBox1.SelectedValue.ToString)
        Else
            RemoveHandler comboBox1.SelectedIndexChanged, _
                      New EventHandler(AddressOf ComboBox_SelectedIndexChanged)
        End If
End Sub


參考:
DataGridViewComboBoxEditingControl 類別
DataGridView中comboBox(DataGridViewComboBoxColumn)的事件编写
DataGridViewComboBoxColumn的事件??
如何製作DataGridViewComboBoxColumn SelectedIndexChange
如何给DataGridViewComboBoxColumn写事件
DataGridViewComboBoxColumn的事件
DataGridViewEditingControlShowingEventArgs.Control Property
DataGridViewComboBoxColumn的事件??
DataGridViewComboBoxColumn multiple click SelectedIndexChanged event
如何处理DataGridViewComboBoxCell的SelectedIndexChanged事件?
datagridview 選擇 combobox 值 , 自動帶出資料
commit changed in DataGridView when selection changed in ComboBox
DataGridViewComboBoxColumn Selection Changed

ProcessCmdKey方法让DataGridView按Enter回车键转到下一列的格
(讓ComboBoxColumn在下拉選項時, 解決出現二種模式...)

[技巧] DataGridView 遇到 ReadOnly 則跳過... (不停留 StopTab)


    Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, ByVal keyData As System.Windows.Forms.Keys) As Boolean
        If keyData = Keys.Enter Then
            If Me.ActiveControl.Name = "DataGridView1" Then
                If CType(Me.ActiveControl, DataGridView).CurrentCell.ReadOnly = True Then
                    SelectNextCell()
                    Return True
                End If
            End If

            'Return MyBase.ProcessCmdKey(msg, keyData)
            SendKeys.Send(vbTab)
            Return True
        End If

        If keyData = Keys.Tab Then
            If Me.ActiveControl.Name = "DataGridView1" Then
                If CType(Me.ActiveControl, DataGridView).CurrentCell.ReadOnly = True Then
                    SelectNextCell() 'SendKeys.Send(Keys.Enter)
                    Return True
                End If
            End If

            Return MyBase.ProcessCmdKey(msg, keyData)
            'SendKeys.Send(vbTab)
            Return True
        End If

        Return MyBase.ProcessCmdKey(msg, keyData)
    End Function


    Public Function SelectNextCell() As Boolean
        Dim row As Integer = DataGridView1.CurrentCell.RowIndex
        Dim column As Integer = DataGridView1.CurrentCell.ColumnIndex
        Dim startingCell As DataGridViewCell = DataGridView1.CurrentCell

        Do
            column += 1
            If column = DataGridView1.Columns.Count Then
                column = 0
                row += 1
            End If
            If row = DataGridView1.Rows.Count Then
                row = 0
            End If
        Loop While DataGridView1(column, row).ReadOnly = True AndAlso DataGridView1(column, row) IsNot startingCell
'Loop While (DataGridView1.Columns(column).Visible = False OrElse DataGridView1(column, row).ReadOnly = True) AndAlso DataGridView1(column, row) IsNot startingCell


        If DataGridView1(column, row) Is startingCell Then
            Return False
        End If

        '這邊要注意起啟的位置,如果Column(0)為ReadOnly,則起啟就設置如下註解! 
        DataGridView1.CurrentCell = DataGridView1(1, row) 'DataGridView1(0, row)


        '如果是要真的讓ReadOnly都直接下一行下一列,則如下的Code才最正確
        DataGridView1.CurrentCell = DataGridView1(column, row)
        Return True
    End Function

[C#]
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace System.Windows.Forms
{
  class MyDataGridView : DataGridView
  {
    protected override bool ProcessDialogKey(Keys keyData)
    {
      if (keyData == Keys.Enter || keyData == Keys.Tab)
      {
        MyProcessTabKey(Keys.Tab);
        return true;
      }
      return base.ProcessDialogKey(keyData);
    }

    protected override bool ProcessDataGridViewKey(KeyEventArgs e)
    {
      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Tab)
      {
        MyProcessTabKey(Keys.Tab);
        return true;
      }
      return base.ProcessDataGridViewKey(e);
    }

    protected bool MyProcessTabKey(Keys keyData)
    {
      bool retValue = base.ProcessTabKey(Keys.Tab);
      while (this.CurrentCell.ReadOnly)
      {
        retValue = base.ProcessTabKey(Keys.Tab);
      }
      return retValue;
    }
  }
}

備註:
如粉紅標記部份,假設有某欄位的visible=false
則必須在加上條件判斷 "DataGridView1.Columns(column).Visible = False"
此時黃色標記部份即可移除 ,若不加上粉紅標記部份,又沒加上黃色標記部份
則會發生 "無法將目前的儲存格設定為不可見的儲存格" 的錯誤,因為把 DataGridView1.CurrentCell 定為 Visible = False 的 Cell

參考:
鍵盤輸入的運作方式
DataGridView.ProcessDialogKey 方法
DataGridView.ProcessDataGridViewKey 方法
Control.SelectNextControl 方法
Control.GetNextControl 方法

DataGridView 编辑回车事件
跳到某一格...
.Net 2.0 DataGridView中键盘事件处理方法
Protected Overrides Function ProcessCmdKey 
還少了上下左右的判斷,有需要的自己改寫!
Tab to the next cell in a DataGridView
No Tab Stop DataGridView Column
HOW TO AVOID ENTERING READONLY CELLS ON A DATAGRIDVIEW
Bypass read only cells in DataGridView when pressing TAB key
C# Enter轉Tab,讓MultiLine可換行
Up/Down - Arrow function
WM_KEYDOWN message
DataGridView 控制項 (Windows Form)


[C#]DataGridViewのCell移動をEnterで
DataGridViewでEnterキーを押すと隣のセルにフォーカスが移動されるようにする
svn/ trunk/ ExtControls/ 測試專案/ MyDataGridview.cs
Bypass read only cells in DatagridView when pressing TAB key (good)
关于DataGridView中键盘输入时的单元格跳转
svn/ trunk/ PT.Component/ DataGridView.cs
C#的dataGridView控件實現回車右移控制
ProcessCmdKey方法让DataGridView按Enter回车键转到下一列的格

How catch Enter Key on EndEdit of Datagridview
DataGridView.ProcessDataGridViewKey 方法

[技巧] DataGridViewComboBoxColumn DropDownStyle 下拉式 & AutoCompleteMode


程式碼:
 Private Sub 明細編輯_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles othing,
        '加減項
        Dim columnID As New DataGridViewComboBoxColumn()
        columnID.HeaderText = "加減項"
        columnID.Name = "加減項"
        columnID.DataPropertyName = "加減項"
        'columnID.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
        'columnID.FlatStyle = FlatStyle.Flat
        'columnID.ValueType = GetType(Decimal)

        columnID.DataSource = dt加減項
        columnID.DisplayMember = "中文"
        columnID.ValueMember = "加減"

        'columnID.Items.AddRange(New Object() {0, 1, 2, 3}) '{"TT", "TF", "2F"})
        DataGridView1.Columns.Add(columnID)
    End Sub

   Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing

        If TypeOf e.Control Is DataGridViewComboBoxEditingControl Then
            CType(e.Control, ComboBox).DropDownStyle = ComboBoxStyle.DropDown
            CType(e.Control, ComboBox).AutoCompleteSource = AutoCompleteSource.ListItems
            CType(e.Control, ComboBox).AutoCompleteMode = AutoCompleteMode.SuggestAppend
        End If
    End Sub

參考:
[C#] DataGridView ComboBox 欄位設定自動完成
AutoComplete ComboBox in DataGridView using C#.net Windows Application
C# » How to Create Editable ComboBox in DataGridView
[C#][WinForm]DataGridView中使DataGridViewComboBox可编辑
DataGridView - how to create combobox cell with DisplayStyle ComboBoxList?
看了一篇介绍如何自定义datagridview列的文章,写了一个可输入的combobox列
译文:构建DataGridView的定制NumericUpDown单元格(Cell)和表格列(Column)
扩展 DataGridView 的功能(二)

ProcessCmdKey方法让DataGridView按Enter回车键转到下一列的格
(讓ComboBoxColumn在下拉選項時, 解決出現二種模式...)

Combobox AutoCompleteMode.Suggest Issue (不能DropDown又用Suggest)




The operating system might limit the number of custom strings that it can display at once. For strings that contain a forward slash (/) or backward slash (\), automatic completion appends all characters only up to and including the slash.  只貼上到斜線

2013年4月25日 星期四

[除錯] System.ArgumentException:DataGridViewComboBoxCell 值無效 (1)


程式碼:

        Me.DataGridView1.AutoGenerateColumns = False
        Me.DataGridView1.DataSource = dt

        '加減項
        Dim installss() As Decimal = {-1, 1}
        Dim columnID As New DataGridViewComboBoxColumn()
        columnID.HeaderText = "加減項"
        columnID.Name = "加減項"
        columnID.DataPropertyName = "加減項"
        columnID.ValueType = GetType(System.Decimal)
        columnID.Items.AddRange(installss)  'columnID.Items.AddRange(+1, -1)
        'columnID.Items.AddRange(New Object() {-1, +1,})
        DataGridView1.Columns.AddRange(New System.Windows.Forms.DataGridViewColumn() {columnID})
 

原因:
出现这种问题有两种原因:
1.数据类型不匹配 
2.所赋数据项与绑定的数据源中数据不符 结贴!

此次debug為第一種原因:
資料庫的資料型態為 Decimal(13,6)
.NET的資料型態為 Decimal , Object 皆無法成功。

解決(一):
改用DataTable方式...
        Me.DataGridView1.AutoGenerateColumns = False
        Me.DataGridView1.DataSource = dt

        Dim dtttt As DataTable = New DataTable
        dtttt.Columns.Add("加減項", GetType(Decimal))
        dtttt.Columns.Add("中文", GetType(String))
        dtttt.Rows.Add(+1, "加")
        dtttt.Rows.Add(-1, "減")
        dtttt.TableName = "XXX"

        '加減項
        Dim installss() As Decimal = {-1, 1}
        Dim columnID As New DataGridViewComboBoxColumn()
        columnID.HeaderText = "加減項"
        columnID.Name = "加減項"
        columnID.DataPropertyName = "加減項"
        columnID.ValueType = GetType(System.Decimal)

        columnID.DataSource = dtttt
        columnID.DisplayMember = "中文"
        columnID.ValueMember = "加減項"

        DataGridView1.Columns.AddRange(New System.Windows.Forms.DataGridViewColumn() {columnID})

解決(二):
應該要依這個link的方式(類別),來繫結資料... """待測試"""
如何在程式內,直接給DataGridViewComboBoxColumn的下拉選單內容?
如何自訂DataGridView中DataGridViewComboBoxColumn物件
如何自訂DataGridView中DataGridViewComboBoxColumn物件

參考:
C# 類型的預設值 (C# 參考)  string就不會出錯,但數值有預設值,所以會出錯...

DataGridView 資料行下拉選單,資料繫結階段顯示 DataGridViewComboBoxCell 值無效
DataGridViewComboBoxCell.GetFormattedValue 方法
给DataGridViewComboBoxCell赋值的问题!
DataGridViewComboBoxColumn值无效
DataGridViewComboBoxColumn值无效
解决方法就是在窗体的构造函数里添加如下代码:
this.dataGridView1.DataError += delegate(object sender, DataGridViewDataErrorEventArgs e) { };

DataGridViewComboBoxColumn的使用 (高招)
Mapping CLR Parameter Data
DataGridView 使用问题
SQL Server 資料型別對應 (ADO.NET).
DataGridView.DataError 事件
DataGridViewDataErrorContexts 列舉型別

Non-String values in DataGridViewComboBoxColumn causing DataErrors in DataGridView
System.ArgumentException:DataGridViewComboBoxCell 值無效 (2)
DataGridViewComboBoxCell 值無效
DataGridView中comboBox数据绑定的问题
DataGridView 的DataGridViewComboBoxColumn 無效值問題

SqlServer中decimal(numeric )、float 和 real 数据类型的区别
What is a good mapping of .NET decimal to SQL Server decimal?

[除錯] System.ArgumentException:DataGridViewComboBoxCell 值無效 (2)

程式碼:
        Me.DataGridView1.AutoGenerateColumns = False
        Me.DataGridView1.DataSource = dt

        Dim installs(dt供應商.Rows.Count - 1) As String
        Dim x As Integer = 0
        For Each dr As DataRow In dt供應商.Rows
            installs(x) = dr(0).ToString
            x += 1
        Next

        '供應商
        Dim columnSex As New DataGridViewComboBoxColumn()
        columnSex.HeaderText = "供應商別"
        columnSex.Name = "供應商別"
        columnSex.DataPropertyName = "供應商別"
        columnSex.ValueType = GetType(String)  'dt供應商.Rows(0).Item(0).GetType()
        columnSex.Items.AddRange(installs)
        DataGridView1.Columns.AddRange(New System.Windows.Forms.DataGridViewColumn() {columnSex})

原因:
出现这种问题有两种原因:
1.数据类型不匹配 
2.所赋数据项与绑定的数据源中数据不符 结贴!

此次debug為第二種原因:
資料庫某一個Record的其供應商別的欄位的值為 X
而DataGridViewComboBoxColumn的Items的值為 Y,Z,S 不包含X


解決(一):
繫結資料庫dt時,必須確定資料庫的值可與DataGridViewComboBoxColumn的Items匹配。
只要把資料庫的值改掉就好。 也就是說必須確定資料庫的值不會是Items匹配以外的值。

解決(二):
直接在事件處理掉 ""DataGridView1_DataError""
就不會出現錯誤訊息,只要不影響作業!
但是若資料庫的數值型態與.NET數值型態不符時,雖然錯誤訊息已隱藏!
但當在選擇items時,會無法正常運作。
即使你選擇了某值,而此值因為違反規則,所以又會變成空白...

Private Sub DataGridView1_DataError(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) Handles DataGridView1.DataError
        'e.ThrowException = False

        'If Me.DataGridView1.Columns(e.ColumnIndex).Name = "供應商別" Then
               'do something here
               '留空, 只要輸入符合欄位型態,(為繫結資料來源內的項目)可正常輸入!
        'End If

End Sub
可參考(DataGridViewComboBoxColumn的数据源有关问题)
DataGridViewDataErrorContexts 列舉型別

圖示:
原始資料(From DataBase)
紅色部份為不存在於繫結來源內的項目


沒有加入事件 DataGridView1_DataError (在AA03 就開始出現錯誤訊息...)

加入事件 DataGridView1_DataError

選擇來源為資料繫結內的項目-001

選擇來源為繫結資料內的項目-002

輸入自定義文字-001

輸入自定義文字-002 ∵不符合原始繫結資料內的項目,故還原為空白!


參考:
C# 類型的預設值 (C# 參考)  string就不會出錯,但數值有預設值,所以會出錯...

Datagridview ComboBoxColumn Nullable
DataGridViewComboBoxCell.GetFormattedValue 方法
给DataGridViewComboBoxCell赋值的问题!
DataGridViewComboBoxColumn值无效
DataGridViewComboBoxColumn值无效
解决方法就是在窗体的构造函数里添加如下代码:
this.dataGridView1.DataError += delegate(object sender, DataGridViewDataErrorEventArgs e) { };

DataGridViewComboBoxColumn的使用 (高招)
Mapping CLR Parameter Data
DataGridView 使用问题
DataGridView.DataError 事件
Non-String values in DataGridViewComboBoxColumn causing DataErrors in DataGridView
System.ArgumentException:DataGridViewComboBoxCell 值無效 (1)
DataGridViewComboBoxCell 值無效
DataGridView中comboBox数据绑定的问题
DataGridView 的DataGridViewComboBoxColumn 無效值問題

SqlServer中decimal(numeric )、float 和 real 数据类型的区别
What is a good mapping of .NET decimal to SQL Server decimal?


2013年4月15日 星期一

[除錯] Web Services (ASP.NET + IIS) 出現如msgbox的訊息框,需透過 WebForm 的 Response.Write 即可!

流程:
WinForm (client) --network-- (server) Web Service --- Class --- DB


錯誤訊息:(在 Class msgbox時所引發的錯誤。)
當應用程式不使用 UserInteractive 模式執行時,顯示強制回應對話方塊或表單不是有效的作業。指定 ServiceNotification 或 DefaultDesktopOnly 樣式以顯示來自服務應用程式的告知。


實作:(寫在class裡的一段程式)
Try

Catch e As Exception
          'MsgBox(e.ToString) <-- 錯誤訊息的原因
          HttpContext.Current.Response.Write(e.ToString)

Finally
          '
End Try


參考:
ASP.NET 使用 MsgBox 顯示提示訊息
在 ASP.NET 也能使用 MessageBox 彈出對話方塊的功能
讓 ASP.NET 也可以使用 MsgBox 方法
Class類別中的Response、Server、Request未宣告解決方法(使用HttpContext.Current屬性)
SQL Injection技巧大全 <-- 用來測試 Sql select 的強度!!

2013年4月2日 星期二

[SQL] 一次更新多筆資料列 SqlServer2005 & SqlServer 2008

Table:


SQL:
            sqlQuery = "UPDATE [attend] SET " & _
            " hr = case type when '事假' then @hr事 " & _
            "when '病假' then @hr病 when '加班' then 0 when '遲到' then @hr遲 End, " & _
            " hrY = case type when '事假' then @hrY事 " & _
            "when '病假' then @hrY病 when '加班' then @hrY加 when '遲到' then 0 End, " & _
            " times = case type when '事假' then 0 " & _
            "when '病假' then 0 when '加班' then 0 when '遲到' then 0 End, " & _
            " timesY = case type when '事假' then 0 " & _
            "when '病假' then 0 when '加班' then @timesY加 when '遲到' then @timesY遲 End, " & _
            " times730 = case type when '事假' then 0 " & _
            "when '病假' then 0 when '加班' then @times730加 when '遲到' then 0 End, " & _
            "modifyDate=@ModifyDate,modifyUserName=@ModifyUserName," & _
            "modifyUserID=@ModifyUserID,SysModifyDate=@SystemModifyDate " & _
            "WHERE type in ('事假','病假','加班','遲到') AND ym = @ym AND staff_sn = @staff_sn;"

參考:
[SQL]INSERT & UPDATE multiple records
SQL 同一資料表中,大量更新?
如何一次更新同的欄位的多筆資料
一次更新多筆資料
一次新增多筆資料列 SqlServer2005 & SqlServer 2008
[SQL]將表格橫向呈現

2013年4月1日 星期一

[SQL] 一次新增多筆資料列 SqlServer2005 & SqlServer 2008

2005用法:
Previous method 1:
USE YourDB
GO
INSERT INTO MyTable (FirstColSecondCol)VALUES ('First',1);INSERT INTO MyTable (FirstColSecondCol)VALUES ('Second',2);INSERT INTO MyTable (FirstColSecondCol)VALUES ('Third',3);INSERT INTO MyTable (FirstColSecondCol)VALUES ('Fourth',4);INSERT INTO MyTable (FirstColSecondCol)VALUES ('Fifth',5);GO


Previous method 2:
USE YourDB
GO
INSERT INTO MyTable (FirstColSecondCol)SELECT 'First' ,1UNION ALLSELECT 'Second' ,2UNION ALLSELECT 'Third' ,3UNION ALLSELECT 'Fourth' ,4UNION ALLSELECT 'Fifth' ,5
GO



CODE:
            sqlQuery = "INSERT into [attend] " & _
            "SELECT @staff_sn ,@ym,'事假',@hr事,'0',@hrY事,'0','0', @CreateDate, @CreateUserID,@CreateUserName,@ModifyDate," & _
            "@ModifyUserID, @ModifyUserName, @SystemModifyDate" & _
            " UNION ALL " & _
            "SELECT @staff_sn ,@ym,'病假',@hr病,'0',@hrY病,'0','0', @CreateDate, @CreateUserID,@CreateUserName,@ModifyDate," & _
            "@ModifyUserID, @ModifyUserName, @SystemModifyDate" & _
            " UNION ALL " & _
            "SELECT @staff_sn ,@ym,'加班',0,'0',@hrY加,@timesY加,@times730加, @CreateDate, @CreateUserID,@CreateUserName,@ModifyDate," & _
            "@ModifyUserID, @ModifyUserName, @SystemModifyDate" & _
            " UNION ALL " & _
            "SELECT @staff_sn ,@ym,'遲到',@hr遲,'0','0',@timesY遲,'0', @CreateDate, @CreateUserID,@CreateUserName,@ModifyDate," & _
            "@ModifyUserID, @ModifyUserName, @SystemModifyDate;"


參考:
SQL Insert Into
SQL UNION
INSERT多筆資料
SQL SERVER – 2008 – Insert Multiple Records Using One Insert Statement – Use of Row Constructor
[MS SQL] [SQL]利用UNION ALL整合統計合併資料
一次更新多筆資料列 SqlServer2005 & SqlServer 2008