顯示具有 ERPsys 標籤的文章。 顯示所有文章
顯示具有 ERPsys 標籤的文章。 顯示所有文章

2013年5月21日 星期二

[學習] 四捨五入

[SQL]
select round(1.5446,2)
1.5400

select round(round(1.5446,3),2)
1.5500

select CAST(1.5446 AS decimal(9,2))
1.54

select CAST(1.546 AS decimal(9,2))
1.55

*資料型態decimal
  -生產數、工作分鐘 

統計數 =  Convert(Decimal(18,4) , 生產數 / 工作分鐘) * 60

[VB]
Module Module1
    Sub Main()
        Console.WriteLine((0.46).ToString("0"))
        'Console.WriteLine((1.45).ToString("0.0"))
        Console.WriteLine((0.5).ToString("0"))

        Console.WriteLine((0.46).ToString("f"))
        Console.WriteLine((0.5).ToString("f"))

        Console.WriteLine((4.625).ToString("0.00"))
        Console.WriteLine((4.645).ToString("0.00"))

        Console.WriteLine((4.625).ToString("f2"))
        Console.WriteLine((4.645).ToString("f2"))

        'Console.WriteLine((1.5).ToString("0"))
        Dim a As Double = 0.45
        Dim b As Decimal = 0.46
        'Dim c As Decimal = 4.625
        Console.WriteLine(Math.Round(a, 0, MidpointRounding.AwayFromZero))
        Console.WriteLine(Math.Round(b, 0, MidpointRounding.AwayFromZero))
        Console.WriteLine(Math.Round(4.625, 2, MidpointRounding.AwayFromZero))
        Console.WriteLine(Math.Round(CDec(4.645), 2, MidpointRounding.AwayFromZero))
        Console.Read()
    End Sub
End Module

-----------------

1. 整數以下四捨五入
     int(46410*0.05+0.5)=2321

2. 例 : 12.346 四捨五入至小數點以下一位
     int(12.346*10+0.5)/10=12.3

3. 例 : 12.346 四捨五入至小數點以下二位
     int(12.346*100+0.5)/100=12.35

參考:
浮點數計算結果更接近正解? 算錢用浮點,遲早被人扁

access中含四舍五入取值方法的查询sql语句
正確的四捨五入

[WIKI]數值簡化規則
C# Round (四捨五入) 使用 ToString()
利用VB.NET Format函数实现四舍五入功能
格式化输出-数字.ToString
c#中的常用ToString()方法总结
好用的string.Format或ToString()格式化字串的方法
[C#]簡單快速將各種數值字數轉成數字(string to int)
C#,double和decimal数据类型以截断的方式保留指定的小数位数

 '四捨五入
Public Function Round45(ByVal dblValue As Double) As Long
     Round45 = Fix(dblValue + 0.5 * Math.Sign(dblValue))
End Function

C#沒有四捨五入?只有五捨六入的涵數?
只要試試4.625與4.645兩個都對, 那才是真的對了

decimal 小數點位數 四捨五入
[C#]無條件進位,無條件捨去及四捨五入寫法

[ACCESS]單精準數運算Round取到小數位數問題
Round 函數

How To Implement Custom Rounding Procedures

2013年3月24日 星期日

[技巧] 動態更改 ReportViewer.LocalReport.ReportPath


Me.ReportViewer1.Reset()
'組件路徑 (不必將 report檔 ".rdlc" 丟到實際資料夾底下...)
Me.ReportViewer1.LocalReport.ReportEmbeddedResource = "eHRsys.Report2.rdlc"  

Note:
eHRsys.Report2.rdlc
組件名稱.檔案名稱.檔案副檔名

參考:
[MSDN]LocalReport.ReportPath 屬性
如何動態更換ReportViewer的RDLC及DataSource
收藏 RDLC动态绑定问题
如何使用LocalReport - WebForm (3)
动态的rdlc报表
顯示整頁模式
The WinForms ReportViewer and Multiple Report Definition Files
Binding DataSet and Generic *.rdlc Reports to a ReportViewer at Runtime

2013年2月19日 星期二

[學習] 讓視窗保持在最上層


(一)
Dim frm備註 As New 詢價單備註編輯
frm備註.MyCallForm = Me
frm備註.ShowDialog()




(二)
此段程式碼是寫在同一個視窗(Form)

ShowDialog 的焦點會一直在被開啟的Form上
與之不同的是 Show 的焦點不會在開啟的Form上

所以當開啟時若要一直在焦點上的話
就必須在主視窗的Activated事件下寫段程式

又因為被開啟的Form 並不是MDI表單
所以必須在 Application.OpenForms 下去搜尋

在圖一的紅色框的範圍內連點兩下,則會使主視窗縮放
在紅色框外及黃色框外的範圍都無法點擊
雖然可點擊黃色框內的 button,但都是沒有反應的(ex:會更新主視窗的資料)
應該是因為 Activated 事件觸發後,其它事件(或反應)就會被攔截掉...(尚待解釋)
而 ShowDialog 則除本視窗外,其它視窗都無法點擊

Private Sub Button8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button8.Click

     Dim frm As New 詢價單費用編輯
     'frm.TopMost = True
     'frm.Owner = Me.ParentForm
     'frm.Parent = Me.ParentForm
     'frm.Focus()
     'frm.Activate()
     frm.Show()
End Sub



Private Sub 詢價單資料輸入作業_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
        For Each f As Form In Application.OpenForms
            If f.Text.Equals("詢價單費用編輯") Then
                f.Activate()
                Exit For
            End If
        Next
End Sub




(三)
若要讓視窗長駐最上層
則使用 TopMost = True
此時的可以點擊其它視窗
只是被開啟的視窗會一直長駐在最上層而己
即使使用者切換至其它應用程式



Private Sub Button8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button8.Click

     Dim frm As New 詢價單費用編輯
     frm.TopMost = True
     'frm.Owner = Me.ParentForm
     'frm.Parent = Me.ParentForm
     'frm.Focus()
     'frm.Activate()
     frm.Show()
End Sub




而(一)及(二)
當使用者點選其它應用程式時,並不會顯示在最上層。



參考:
vb.net find form by title and edit control
VB.net視窗控制問題
利用SetWindowPos使表單永遠放到最上層!
如何在VB裡讓程式表單能夠最上層顯示
如何將 Form 顯示在最上層?
如何顯示其他Form卻又不讓其獲得Focus?
vb.net 轉移程式焦點
VB.Net Form關閉按鈕以及最上層顯示問題
請問如何讓開啟的form只在此視窗中最上層顯示
請問視窗最上層的問題
最上層FORM的鎖定
VB.Net Form顯示為最上層
當程式的前景被其他程式拿走時判斷並拿回前景
[C#]透過 SHDocVw 與 GetForegroundWindow 取得正在使用的 Internet Explorer 網址
[VB.NET]把.NET視窗嵌入.NET視窗或控制項

2013年1月23日 星期三

[技巧] ReportViewer 動態改變字型大小 change/modify dyanamically/programmatically rdlc font/size

原因:
當某些欄位的文字長度超過rdlc設計時的文字方塊大小
列印時欄位便會自動擴大,因而造成報表跑位(拉長或拉寬) or 多出一頁的錯誤

解決:
透過動態改變字型大小即可解決
在文字方塊 - 屬性 - Font - FontSize 運算式
=iif(Len(Parameters!Report_Parameter_0.Value)>= 200,10,12) & "pt"

當參數值Report_Parameter_0 經過 Len()函式 運算出來的 字串長度 > 200 時
設定字型為 10pt Else 設定字型為 12pt


它解:
一、載入rdlc前,改修rdlc(xml)

二、寫在 rdlc code

2013年1月6日 星期日

[技巧] N個控制項驗證寫在同一個事件處理時, 判斷是由哪個控制項觸發事件

[VB.NET]
Private Sub ComboBox_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles ComboBox2.Validating, ComboBox1.Validating, ComboBox3.Validating, ComboBox4.Validating
        'MsgBox(e.ToString)
        'MsgBox(sender.ToString)
        'Exit Sub

        '避免視窗關閉時(引發驗證事件)
        If frmClose = True Then
            Exit Sub
        End If

        '表示都沒有更動, 所以也就不需要再做下面的判斷 -> 新值 = 舊值
        If Me._btnOperation = "update" AndAlso ComboBox1.Text.Trim = Trim(ComboBox1.Tag) AndAlso _
            ComboBox2.Text.Trim = Trim(ComboBox2.Tag) AndAlso _
            ComboBox3.Text.Trim = Trim(ComboBox3.Tag) AndAlso _
            ComboBox4.Text.Trim = Trim(ComboBox4.Tag) Then
            Exit Sub
        End If
        'MsgBox(e.ToString)

        '取得目前焦點位置....
        'MsgBox(CType(sender, Control).Name)
        'Exit Sub

        If (CType(sender, Control).Name = "ComboBox2" OrElse CType(sender, Control).Name = "ComboBox3") _
        AndAlso Me._btnOperation = "update" AndAlso Me.DataGridView1.Rows.Count > 0 _
        AndAlso (ComboBox2.Text.Trim <> Trim(ComboBox2.Tag) OrElse _
                         ComboBox3.Text.Trim <> Trim(ComboBox3.Tag)) Then

            MsgBox("有單據明細資料不能修改此欄位, 請重新輸入!")
            ComboBox2.Text = ComboBox2.Tag
            ComboBox3.Text = ComboBox3.Tag
            Exit Sub
        End If


        If _Editing = True Then

            If String.IsNullOrEmpty(Me.ComboBox2.Text) Then
                MsgBox("材質編號空白, 請重新輸入!")
                ErrorProvider1.SetError(Me.ComboBox2, "材質編號空白, 請重新輸入!")
                Me.ComboBox2.Focus()
                Exit Sub
            ElseIf Me.ComboBox2.SelectedIndex = -1 Then
                MsgBox("材質編號不允許自行輸入, 請重新選擇!")
                ErrorProvider1.SetError(Me.ComboBox2, "材質編號不允許自行輸入, 請重新選擇!")
                Me.ComboBox2.Focus()
                Exit Sub
            End If

            If String.IsNullOrEmpty(Me.ComboBox3.Text) Then
                MsgBox("牌價編號空白, 請重新輸入!")
                ErrorProvider1.SetError(Me.ComboBox3, "牌價編號空白, 請重新輸入!")
                Me.ComboBox3.Focus()
                Exit Sub
            ElseIf Me.ComboBox3.SelectedIndex = -1 Then
                MsgBox("牌價編號不允許自行輸入, 請重新選擇!")
                ErrorProvider1.SetError(Me.ComboBox3, "牌價編號不允許自行輸入, 請重新選擇!")
                Me.ComboBox3.Focus()
                Exit Sub
            End If

            If String.IsNullOrEmpty(Me.ComboBox1.Text) Then
                MsgBox("業務員編號空白, 請重新輸入!")
                ErrorProvider1.SetError(Me.ComboBox1, "業務員編號空白, 請重新輸入!")
                Me.ComboBox1.Focus()
                Exit Sub
            ElseIf Me.ComboBox1.SelectedIndex = -1 Then
                MsgBox("業務員編號不允許自行輸入, 請重新選擇!")
                ErrorProvider1.SetError(Me.ComboBox1, "業務員編號不允許自行輸入, 請重新選擇!")
                Me.ComboBox1.Focus()
                Exit Sub
            End If

            If String.IsNullOrEmpty(Me.ComboBox4.Text) Then
                MsgBox("幣別欄位空白, 請重新輸入!")
                ErrorProvider1.SetError(Me.ComboBox4, "幣別欄位空白, 請重新輸入!")
                Me.ComboBox4.Focus()
                Exit Sub
            ElseIf Me.ComboBox4.SelectedIndex = -1 Then
                MsgBox("幣別欄位不允許自行輸入, 請重新選擇!")
                ErrorProvider1.SetError(Me.ComboBox4, "幣別欄位不允許自行輸入, 請重新選擇!")
                Me.ComboBox4.Focus()
                Exit Sub
            End If

            '取消事件
            'e.Cancel = True
        End If

        ErrorProvider1.SetError(Me.ComboBox1, "")
        ErrorProvider1.SetError(Me.ComboBox2, "")
        ErrorProvider1.SetError(Me.ComboBox3, "")
        ErrorProvider1.SetError(Me.ComboBox4, "")
    End Sub


[C#.NET]
        private void txt_訂購單號_Validating(object sender, CancelEventArgs e)
        {
            if (this._Editing==false)
                return;

            //MessageBox.Show(typeof((Control)sender));
            //MessageBox.Show((sender).GetType().ToString());
            //MessageBox.Show(((Control)sender).GetType().ToString());
            //MessageBox.Show(this.ActiveControl.Name);

            //switch (sender.GetType().ToString())
            //{
            //    case "TextBox":
            //        MessageBox.Show("AA");
            //        break;
            //}

            Regex rx;
            if (sender is TextBox)
            {
                //if (((TextBox)sender).Name == "")
                //{

                //}

                switch (((TextBox)sender).Name)
                {
                    case "txt_訂購單號":
                        rx = new Regex(@"^[\S]{1,15}$");
                        if (!rx.IsMatch(txt_訂購單號.Text.Trim()))
                        {
                            MessageBox.Show(
                                this,
                                "訂購單號:不可空白, 長度不可超過15!!",
                                "✚格式化錯誤✚",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                            errorProvider1.SetError(txt_訂購單號, "不可空白, 長度不可超過15!!");
                            //txt_訂購單號.Focus();
                            e.Cancel = true; //按右上角FormClose...會被取消
                        }
                        break;
                    case "txt_AD":
                        rx = new Regex(@"^(25[0-5]|2[0-4]\d|[1]\d{2}|[0-9]{0,2})$");
                        if (!rx.IsMatch(txt_AD.Text.Trim()))
                        {
                            MessageBox.Show(
                                this,
                                "AD:請輸入數值0-255!!",
                                "✚格式化錯誤✚",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                            errorProvider1.SetError(txt_AD, "請輸入數值0-255!!");
                            //txt_AD.Focus();
                            e.Cancel = true; //按右上角FormClose...會被取消
                        }
                        break;
                    case "txt_註記":
                        rx = new Regex(@"^[\S]{0,50}$");
                        if (!rx.IsMatch(txt_註記.Text.Trim()))
                        {
                            MessageBox.Show(
                                this,
                                "註記:長度不可超過50!!",
                                "✚格式化錯誤✚",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                            errorProvider1.SetError(txt_註記, "長度不可超過50!!");
                            //txt_註記.Focus();
                            e.Cancel = true; //按右上角FormClose...會被取消
                        }
                        break;
                    case "txt_客戶訂號":
                        rx = new Regex(@"^[\S]{0,20}$");
                        if (!rx.IsMatch(txt_客戶訂號.Text.Trim()))
                        {
                            MessageBox.Show(
                                this,
                                "註記:長度不可超過20!!",
                                "✚格式化錯誤✚",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                            errorProvider1.SetError(txt_客戶訂號, "長度不可超過20!!");
                            //txt_客戶訂號.Focus();
                            e.Cancel = true; //按右上角FormClose...會被取消
                        }
                        break;
                    case "txt_詢單編號":
                        rx = new Regex(@"^[\S]{0,15}$");
                        if (!rx.IsMatch(txt_詢單編號.Text.Trim()))
                        {
                            MessageBox.Show(
                                this,
                                "詢單編號:長度不可超過15!!",
                                "✚格式化錯誤✚",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                            errorProvider1.SetError(txt_詢單編號, "長度不可超過15!!");
                            //txt_客戶訂號.Focus();
                            e.Cancel = true; //按右上角FormClose...會被取消
                        }
                        break;
                    case "txt_交易條件":
                    case "txt_付款方式":
                        rx = new Regex(@"^[\S]{0,50}$");
                        if (!rx.IsMatch(((TextBox)sender).Text.Trim()))
                        {
                            MessageBox.Show(
                                this,
                                ((TextBox)sender).Tag + ":長度不可超過50!!",
                                "✚格式化錯誤✚",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                            errorProvider1.SetError(((TextBox)sender), "長度不可超過50!!");
                            //txt_客戶訂號.Focus();
                            e.Cancel = true; //按右上角FormClose...會被取消
                        }
                        break;
                    case "txt_訂單金額":
                        //rx = new Regex(@"^(25[0-5]|2[0-4]\d|[1]\d{2}|[0-9]{0,2})$");
                        //if (!rx.IsMatch(txt_訂單金額.Text.Trim()))
                        //{
                        //}
                        decimal decResult = 0;
                        bool decFalg = decimal.TryParse(txt_訂單金額.Text.Trim(), out decResult);
                        if ( !decFalg || decResult < 0)
                        {
                            MessageBox.Show(
                                this,
                                "金額:請輸入正整數!!",
                                "✚格式化錯誤✚",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                            errorProvider1.SetError(txt_訂單金額, "請輸入正整數!!");
                            //txt_AD.Focus();
                            e.Cancel = true; //按右上角FormClose...會被取消
                        }
                        break;
                    case "txt_數量":
                        //rx = new Regex(@"^(25[0-5]|2[0-4]\d|[1]\d{2}|[0-9]{0,2})$");
                        //if (!rx.IsMatch(txt_數量.Text.Trim()))
                        //{
                        //}    
                        int intResult = 0;
                        bool intFalg = int.TryParse(txt_數量.Text.Trim(), out intResult);
                        if ( !intFalg || intResult < 0)
                        {
                            MessageBox.Show(
                                    this,
                                    "數量:請輸入正整數!!",
                                    "✚格式化錯誤✚",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                            errorProvider1.SetError(txt_數量, "請輸入正整數!!");
                            //txt_AD.Focus();
                            e.Cancel = true; //按右上角FormClose...會被取消
                        }                      
                        break;
                    default:
                        break;
                }
            }
            else if (sender is ComboBox)
            {
                switch (((ComboBox)sender).Name)
                {
                    case "cmb_客戶編號":
                    case "cmb_業務編號":
                    case "cmb_抬頭編號":
                    case "cmb_流程編號":
                    case "cmb_幣別編號":
                    case "cmb_銀行編號":
                        //rx = new Regex(@"^[\S]{0,20}$");
                        //if (!rx.IsMatch(txt_客戶訂號.Text.Trim()))
                        //}

                        if(((ComboBox)sender).SelectedIndex == -1)
                        {
                            MessageBox.Show(
                                this,
                                ((ComboBox)sender).Tag + ":請從項目中選擇!!",
                                "✚格式化錯誤✚",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                            errorProvider1.SetError((Control)sender, "請從項目中選擇!!");
                            //cmb_客戶編號.Focus();
                            e.Cancel = true; //按右上角FormClose...會被取消
                        }
                        break;

                    default:
                        break;
                }
            }
         
        }

        private void txt_訂購單號_Validated(object sender, EventArgs e)
        {
            //MessageBox.Show(sender.ToString());
            errorProvider1.SetError((Control)sender, "");
            //errorProvider1.SetError(txt_訂購單號, "");
            //errorProvider1.SetError(txt_AD, "");
            //errorProvider1.SetError(txt_註記, "");
            //errorProvider1.SetError(cmb_客戶編號, "");
            //errorProvider1.SetError(cmb_業務編號, "");
            //errorProvider1.SetError(txt_客戶訂號, "");
        }

參考:
Control.Validating 事件
Control.GotFocus 事件
判斷焦點位置
[C#.NET][VB.NET] 如何設定 控制項陣列 / 動態加入控制項
[C#] 動態 button 和事件
C#動態控制項陣列化

2013年1月4日 星期五

[技巧] BindingSource.item 透過[欄位名稱] 取代 [索引值] 來取值...

假設DB一筆Row共用100個欄位(從1開始~100)
而你想要的值在第37個位置(從0開始~99)
則bs的屬性item取值如下:

(法一) 這種方式是必須去算所要的值在第幾個索引,算到頭都昏了!!
bindingsource.item(0)(37).tostring

(法二) 這種方式方便多了,當你將DB bind到 bs時,也會有欄位名稱!!
bs.item(0)("欄位名稱").tostring

ex:欄位名稱為 "匯率"
bs.item(0)("匯率").tostring

Note:
datatable,dataset,datagridview,etc... 等同道理!

[C#]
((DataRowView)bs_印字[bs_印字.Position])["MARK1"]

參考:
BindingSource.Item 屬性
http://hi.baidu.com/1981633/item/88a5cb89c071d02b110ef30c
BindingSource使用模式 - Data Binding基礎知識 (一)

2013年1月3日 星期四

[技巧] DataTable - 查詢篇 (找出所在的索引位置) 並刪除


程式:
'Dim row() As DataRow = Me.Head_dt.Select("詢價單號 = 'AA01'")
Dim row() As DataRow = Me.Head_dt.Select("詢價單號 = '" & TextBox1.Text.Trim & "'")
MsgBox(Me.Head_dt.Rows.IndexOf(row(0)))

  Note:
Select 方法會回傳 DataRow 陣列 (多筆) 
Dim row() As DataRow = Me.Head_dt.Select("詢價單號 = 'AA01'")

其它:
'MsgBox(Me.Head_dt.Select("詢價單號 = 'AA02'").Length) <-- 總共找到幾筆資料
'Me.Head_dt.Rows.RemoveAt(Me.Head_dt.Rows.IndexOf(row(0))) <-- 刪除此索引值的Row

刪除另解:DataRow會連動底層DataTable... 應該是 call by refence
        Dim dtrow() As DataRow = dt.Select("詢價單號 = '" & DataGridView1.CurrentRow.Cells("詢價單號").Value.ToString & "' and 序號 = " & DataGridView1.CurrentRow.Cells("序號").Value.ToString & "")
        'dt.Rows(0)(0) = "AA0000"
        dt.Rows(0).Delete()
从 DataTable 对象中删除 DataRow 对象 遇到的问题

備註:
若是日期格式,則 # 欄位資料 #

for i as integer = 0 to row.GetUpperBound(0)
    msgbox(row(i)("欄位名稱").Tostring)
next

參考:
How to find index of a row based on the object value? (C#)
[ADO.NET] 如何使用 DataTable / 搜尋 過濾 資料
檢視 DataTable 中的資料
DataTable Select的陷阱
DataTable (Select, Find, Compute and Linq)
Linq實踐系列(1):一句代碼實現DataTable全文搜索(Full Text Search)
在DataTable中查询应该注意的问题
对DataTable数据进行查询过滤
DataTable中的select()用法
DataTable.Compute 方法

參考2:
about DataTable.Select("FieldName=日期時間")
.net datatable 的 select 敘述使用 SQLSERVER datetime
Select in DataTable with condition on DateTime column
SUBSTRING LIKE
Datatable.Select 的運算式用法
Linq小技巧:日期處理
SQL函數 查詢SQL資料欄位相符的字串
MSSql 中Charindex ,Substring的使用
CHARINDEX (Transact-SQL)

2012年12月26日 星期三

[學習] decimal 小數點位數 四捨五入

[SQL]
select round(1.5446,2)
1.5400

select round(round(1.5446,3),2)
1.5500

select CAST(1.5446 AS decimal(9,2))
1.54

select CAST(1.546 AS decimal(9,2))
1.55


*資料型態decimal
  -生產數、工作分鐘 

SELECT 生產數,工作分鐘,
生產數/工作分鐘*60,
Convert(Decimal(18,4),生產數/工作分鐘)*60,
floor(convert(decimal(18,4),生產數/工作分鐘)*60),
floor(生產數/工作分鐘*60),

Round(生產數/工作分鐘*60,1) AS 小數第1位,
Round(生產數/工作分鐘*60,4) AS 小數第4位,

(生產數/工作分鐘*60*10+0.5)/10,
FLOOR(生產數/工作分鐘*60*10+0.5)/10
FROM tblA



[ACCESS]

SELECT 生產數,工作分鐘,
 Round(生產數/工作分鐘*60,1),
 Int(CDBL(生產數/工作分鐘)*60*10+0.5)/10 ,
 Int((生產數/工作分鐘)*60*10+0.5)/10 
 FROM tblA

互相比對結果值(EXCEL)








[VB]
小數點表示法
^[0-9]+(.[0-9]{1,6})?$

通過
0
0.
0.0
0.123456
123456789.123456

-----------------

資料庫 insert 時,decimal型態自動進位(四捨五入)。
假設小位數到3,資料庫 decimal型態就必須設置小數點到3。
當然在程式設計時,也必須 decimal 型態 到小數點3。

-----------------

1. 整數以下四捨五入
     int(46410*0.05+0.5)=2321

2. 例 : 12.346 四捨五入至小數點以下一位
     int(12.346*10+0.5)/10=12.3

3. 例 : 12.346 四捨五入至小數點以下二位
     int(12.346*100+0.5)/100=12.35

參考:
浮點數計算結果更接近正解? 算錢用浮點,遲早被人扁

2012年12月25日 星期二

[SQL] bit欄位型態, 插入Insert 與 讀取Select的值為1與0, 而不是True與False...

insert/update:
資料必須為 1,0 而不是 True,False
Convert.ToInt16(CheckBox1.Checked)  轉換為 1,0

select:
資料會自動轉為 True,False

備註:
欄位 Uses , Char(255)
SELECT CASE Uses WHEN 'T' THEN true ELSE 'false'

參考:
bit和 bool的问题
SQL Server数据库中bit字段类型使用时的注意事项
boolean插入mysql中bit类型,读出来是false和true,但是用false查询用,是空的  <-- 要用 1,0 查詢
how-to-add-custom-checkbox-column-to-datagridview

Convert.ToBoolean

2012年12月24日 星期一

[除錯] 字串未被辨認為有效的 DateTime

說明:
當資料欄位型態為 DateTime ,而資料欄卻沒有資料 DBNull
取出資料存在陣列,其在陣列的值依然為 DBNull 而非 Empty
當DataBindSource某欄位其資料型態為DateTime
並且要將陣列 "日期資料 DBNull / Empty" 配置過去時
便會發生 Error Msg : 字串未被辨認為有效的 DateTime

解決方式:
塞入"無意義的"日期字串, 但未來要使用時必須判別說 "1900/1/1" 便是...
不一定是最好方法,評估一下便可適用專案解法...

                    If i = 58 OrElse i = 63 OrElse i = 66 Then
                        MsgBox(bs.Item(bs.Position)(i).ToString)
                        'MsgBox(bs.Item(bs.Position)(i).GetType.ToString)
                        'bs.Item(bs.Position)(i) = CDate(bsReset(i).ToString).Date
                        If bs.Item(bs.Position)(i).GetType.ToString = "System.DBNull" Then
                            'MsgBox("A")
                            bs.Item(bs.Position)(i) = "1900/01/01" '暫時的解法
                        Else
                            '
                            bs.Item(bs.Position)(i) = bsReset(i).ToString
                        End If
                        MsgBox(bs.Item(bs.Position)(i).ToString)
                    Else
                        bs.Item(bs.Position)(i) = bsReset(i).ToString
                    End If

正解:
控制項.DataBindings.Add 當繫結格式為 DateTime 時,可以輸入空白!

參考:
[SQLite]字串未被辨認為有效的 DateTime?
字串未被辨認為有效的DateTime
DateTime的的問題:字串為辯認為有效的DateTime。
字串轉DateTime的問題

[C#]
((DataRowView)bs_印字[bs_印字.Position])["MARK1"]

其它(日期)參考:
時間格式及方法運用
標準日期和時間格式字串
DateTime.GetDateTimeFormats 方法
DateTimeFormatInfo 類別
用DateTimeFormatInfo格式化日期时间(C#)
AM and PM with "Convert.ToDateTime(string)"
how get a.m. p.m. from DateTime?
自訂日期和時間格式字串
datetime.now first and last minutes of the day
SQL时间类型(DateTime)模糊查询及Between
善用 SQL Server 中的 CONVERT 函數處理日期字串
[SQL]使用BETWEEN要注意的地方
[筆記] SQL - between

2012年12月23日 星期日

[學習] CheckedChanged 與 CheckedStateChanged 的區別

CheckedChanged 
值: True / False

CheckedStateChanged  
值: CheckState.Indeterminate(會打勾 並且會有灰色網格背景)
      / CheckState.Unchecked / CheckState.Checked

事件觸發:
從控制項改變值 或 從程式改變值
兩者事件都會觸發


'做驗證時,千萬別用 CheckedChanged 與 CheckedStateChanged 會進入無窮迴圈XD
Private Sub CheckBox2_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles CheckBox2.Validating

     '實現VBA Method [Me.Undo()功能] (解釋--還原到先前的值!!)

     If Me.CheckBox2.CheckState = CheckState.Checked Then
          Me.CheckBox2.CheckState = CheckState.Unchecked
     Else
          Me.CheckBox2.CheckState = CheckState.Checked
     End If
End Sub

NOTE:
如同 TextBox2.undo

參考:
CheckBox.CheckedChanged 事件
CheckBox.CheckStateChanged 事件
checkedBox 属性checkedChanged与checkedStateChanged 区别
VB2010之十二: CheckBox控件

2012年12月20日 星期四

[技巧] DataGridView 實現 CurrentRow 上移 下移

After:


BeFore:



解決:
        bs.DataMember = "Head"
        bs.DataSource = Me.MyCallForm.DataGridView3.DataSource '另一個視窗的DGV3
        DataGridView1.DataSource = bs

(運用bindingsource)
With DataGridView1
     If .Rows.Count > 0 Then
          '到底了 沒辦法再往下移 so 跳開副程式
          If .CurrentRow.Index = .Rows.Count - 1 Then Exit Sub
                Dim a As String = Nothing
                '交換上下 Row的資料
                For i As Integer = 0 To .ColumnCount - 1
                    a = bs.Item(bs.Position + 1)(i).ToString
                    bs.Item(bs.Position + 1)(i) = bs.Item(bs.Position)(i).ToString
                    bs.Item(bs.Position)(i) = a
                Next
          'refresh DGV的資料
          .Refresh()
          'CurrentRow 位置 +1
          .CurrentCell = .Rows(bs.Position + 1).Cells(5)
     End If
End With


(運用datatable)
With DataGridView1
     If .Rows.Count > 0 AndAlso .CurrentRow IsNot Nothing Then
         If .CurrentRow.Index = 0 Then Exit Sub '到頂了 沒辦法再往上移 so 跳開副程式
         dr.ItemArray = DSquotation.Tables("Memo").rows(.CurrentRow.Index - 1).ItemArray
         DSquotation.Tables("Memo").rows(.CurrentRow.Index - 1).ItemArray = DSquotation.Tables("Memo").rows(.CurrentRow.Index).ItemArray
         DSquotation.Tables("Memo").rows(.CurrentRow.Index).ItemArray = dr.ItemArray
      End If

      .Refresh()
      .CurrentCell = .Rows(.CurrentRow.Index - 1).Cells("說明")
End With

參考:

DataGridView 控制項 (Windows Form)
C#中,DataGridView 有 Binding DataSource 的 Rows Add/ Remove 作法
C# Winform DataGridView实现行[Row]的上下移动........
BindingSource Methods
如何手動移動Datagridview的列
求 DataGridview Row 资料任意上下移动对调,该怎么解决
DataGridView手動新增、修改資料列
當控制項已繫結資料時 無法以程式設計的方式將資料列加入 DataGridView 的資料列集合
DataGridView加入欄位
[C#]DataGridView的RowChanged event

兩行 / 兩列 / 行與列 交換
有關資料表的排序問題
如何将DataTable中的某两行记录调换顺序?
dataTable交换两行数据
交换DataTable中的行列位置
DataTable实现列位置交换,用于SQL语句无法解决字段页面显示顺序问题

[C#]
((DataRowView)bs_印字[bs_印字.Position])["MARK1"]

(待運用...)
.select
.copyto

2012年12月17日 星期一

[學習] 字串處理, 切割與截取

取得 "(" 起始位置 index
InStr(ComboBox1.Text, "(")

EX: 123(456)
從字串左邊第一個位置開始截取 直到位置 InStr(ComboBox1.Text, "(") - 1
Microsoft.VisualBasic.Left(ComboBox1.Text, InStr(ComboBox1.Text, "(") - 1)
Result : 123

Microsoft.VisualBasic.Right(cbo_發文者.Text, cbo_發文者.Text.Length-InStr(cbo_發文者.Text, "(")).ToString().Trim(")")
Result : 456

參考:
Functions (Visual Basic)
字串處理
常用VB字串處理函數
字串處理函數
Visual Basic 2005 - 善用 StringBuilder 提升字串處理效率
戰鬥吧!打工戰士!身為工程師須具備的字串處理思維!
在一個字串中插入另一個字串
[C#]簡單快速將各種數值字數轉成數字(string to int)
[隨手筆記]C#字串中的Right方法

[SQL] 多欄位查詢


            Dim str As String = "select * from [A010詢價單資料表-表頭] Where 1=1"

            '選擇哪個查詢條件
            Select Case frm詢價單search.TabControl1.SelectedIndex
                Case 0 '一般
                    'SELECT         外調單號, 預訂交期
                    'FROM             E010外調訂單資料表明細
                    'WHERE         (DATEPART(yy, 預訂交期) = 2008) AND (DATEPART(mm, 預訂交期) = 8)
                    'ORDER BY  預訂交期

                    If frm詢價單search.TextBox1.Text <> "0" Then
                        '日期-年度
                        str = str + " and DATEPART(yy,日期) = " & _
                        frm詢價單search.TextBox1.Text.ToString & ""
                    End If

                    If frm詢價單search.ComboBox1.Text <> "0(全部)" Then
                        '日期-月份
                        str = str + " and DATEPART(mm,日期) = " & _
                        Microsoft.VisualBasic.Left(frm詢價單search.ComboBox1.Text, 2) & ""
                    End If

                    If frm詢價單search.ComboBox2.Text <> "0(全部)" Then
                        '業務員-編號
                        str = str + " and 業務員 = '" & _
                        Microsoft.VisualBasic.Left(frm詢價單search.ComboBox2.Text, InStr(frm詢價單search.ComboBox2.Text, "(") - 1) & "'"
                    End If

                Case 1 '依客戶編號
                    If frm詢價單search.ComboBox3.Text <> "0(全部)" Then
                        'Dim 客戶編號() As String = frm詢價單search.ComboBox3.Text.Split(frm詢價單search.ComboBox3.Text.Split, "(")
                        'str = str + " and 客戶編號 = '" & _
                        ' 客戶編號(0).Trim & "'"

                        str = str + " and 客戶編號 = '" & _
                        Microsoft.VisualBasic.Left(frm詢價單search.ComboBox3.Text, InStr(frm詢價單search.ComboBox3.Text, "(") - 1) & "'"
                    End If

                    '在之前有嚴格判別是否為日期格式 並且不是空白~~
                    If frm詢價單search.TextBox2.Text <> "" And frm詢價單search.TextBox3.Text <> "" Then
                        str = str + " and 日期 between '" & Format(CDate(frm詢價單search.TextBox2.Text), "yyyy/MM/dd") & "' and '" & Format(CDate(frm詢價單search.TextBox3.Text), "yyyy/MM/dd") & "'"
                    End If

                Case 2 '依客戶訂號
                    If Not String.IsNullOrEmpty(frm詢價單search.TextBox4.Text) Then
                        If frm詢價單search.CheckBox1.Checked = True Then
                            str = str + " and 客戶訂號 = '" & _
                            frm詢價單search.TextBox4.Text & "'"
                        Else
                            str = str + " and 客戶訂號 like '%" & _
                            frm詢價單search.TextBox4.Text & "%'"
                        End If
                    End If
                Case 3 '依單號
                    If Not String.IsNullOrEmpty(frm詢價單search.TextBox5.Text) Then
                        str = str + " and 詢價單號 = '" & _
                        frm詢價單search.TextBox5.Text & "'"
                    End If
            End Select

            'sqlQuery
            MsgBox(str)




參考:
[習題]給初學者的範例,多重欄位搜尋引擎 for GridView #1
[MySQL Note.] 資料庫查詢抱怨(刪除線)優化筆記
多欄位的搜尋引擎
改善SQL效能的寫法

[SQL] 判斷日期


Dim str As String = "select * from [A010詢價單資料表-表頭] Where 1=1"

'選擇哪個查詢條件
Select Case frm詢價單search.TabControl1.SelectedIndex
     Case 0 '一般
            'SELECT         外調單號, 預訂交期
            'FROM             E010外調訂單資料表明細
            'WHERE         (DATEPART(yy, 預訂交期) = 2008) AND (DATEPART(mm, 預訂交期) = 8)
            'ORDER BY  預訂交期

      If frm詢價單search.TextBox1.Text <> "0" Then
          '日期-年度
           str = str + " and DATEPART(yy,日期) = " & _
           frm詢價單search.TextBox1.Text.ToString & ""
      End If

      If frm詢價單search.ComboBox1.Text <> "0(全部)" Then
            '日期-月份
             str = str + " and DATEPART(mm,日期) = " & _
             Microsoft.VisualBasic.Left(frm詢價單search.ComboBox1.Text, 2) & ""
      End If

........

參考:
MS-SQL時間格式一覽
MS SQL日期處理方法
MSSQL 抓取現在日期的函數
善用 SQL Server 中的 CONVERT 函數處理日期字串
SQL Server中使用convert转化长日期为短日期
sql使用convert转化长日期为短日期的总结
MS SQL 的datetime 格式轉換
MS SQL日期處理方法-整理(Date and Time Functions Tips)
SQL Server datetime LIKE select?
sql的between與查詢日期範圍
SQL between 日期范围
找出某個日期區間內的資料
各種日期時間計算
日期相減, 算出天數
計算日期的天數
計算兩個日期差距幾天
日期運算的小技巧整理(以起迄日期結束日期為例)
如何下日期相減後得到的是日期
SQL 日期的應用
在SQL中 得到日期 並格式化

TIPS-.NET DateTime Formating
Linq小技巧:日期處理

其它(日期)參考:
時間格式及方法運用
標準日期和時間格式字串
DateTime.GetDateTimeFormats 方法
DateTimeFormatInfo 類別
用DateTimeFormatInfo格式化日期时间(C#)
AM and PM with "Convert.ToDateTime(string)"
how get a.m. p.m. from DateTime?
自訂日期和時間格式字串
datetime.now first and last minutes of the day
SQL时间类型(DateTime)模糊查询及Between
善用 SQL Server 中的 CONVERT 函數處理日期字串
[SQL]使用BETWEEN要注意的地方
[筆記] SQL - between