2022年3月3日 星期四

[除錯] 在建立 XML 讀取器時變更 XmlDictionaryReaderQuotas 物件上使用的 MaxStringContentLength 屬性

 環境:

Client:
Winform 3.5 framework 


錯誤訊息:

將作業 'sqlClient_DapperGetData_WithoutParams' 的回覆訊息本文還原序列化時發生錯誤。讀取 XML 資料時已經超過最大字串內容長度配額 (8192)。在建立 XML 讀取器時變更 XmlDictionaryReaderQuotas 物件上使用的 MaxStringContentLength 屬性,便可以增加此配額。


解決:

修改客戶端app.config [新增紅色部份]

        <bindings>

            <basicHttpBinding>

                <binding name="BasicHttpBinding_IService1" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" >

                <readerQuotas maxDepth="32" maxStringContentLength="10485760" maxArrayLength="10485760" maxBytesPerRead="10485760" maxNameTableCharCount="10485760"/>

                </binding>

            </basicHttpBinding>

        </bindings>


參考:

读取XML数据时,已超过最大字符串内容长度配额(8192)。可以通过更改创建XML阅读器时使用的

VS WCF輸傳限制

BasicHttpBinding.ReaderQuotas 屬性

<readerQuotas>

屬性

屬性

屬性

描述

maxArrayLength

正整數,指定 Windows Communication Foundation (WCF) 接收自用戶端允許的資料陣列長度上限。 預設值為 16384。

maxBytesPerRead

正整數,指定允許每個讀取傳回的位元組上限。 預設值為 4096。

maxDepth

正整數,指定允許每個讀取其巢狀節點深度的上限。 預設值為 32。

maxNameTableCharCount

正整數,指定資料表名稱允許的字元數目上限。 預設值為 16384。

maxStringContentLength

正整數,指定 XML 項目內容中允許的字元數上限。 預設值為 8192。


其它參考:

WCF 傳送大量資料時修改config


[除錯] 請變更物件圖形或增加 MaxItemsInObjectGraph 配額

環境:

Client:
Winform 3.5 framework 


錯誤訊息:

嘗試將訊息還原序列化時,格式子發生例外狀況: 嘗試將參數 http://tempuri.org/:Get鋼管庫存表SqlClientResult 還原序列化時發生錯誤。InnerException 訊息為 '物件圖形中可以序列化或還原序列化的項目數目上限是 '65536'。請變更物件圖形或增加 MaxItemsInObjectGraph 配額。 '。如需詳細資訊,請參閱 InnerException。


解決:

修改客戶端app.config [新增紅色部份]

        <behaviors>

          <endpointBehaviors>

            <behavior name="NewBehavior">

              <dataContractSerializer maxItemsInObjectGraph="2147483647"/>

            </behavior>

          </endpointBehaviors>

        </behaviors>

  

        <bindings>

            <basicHttpBinding>

                <binding name="BasicHttpBinding_IService1" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />

            </basicHttpBinding>

        </bindings>

        <client>

            <endpoint address="http://localhost:1093/Service1.svc"  binding="basicHttpBinding" behaviorConfiguration="NewBehavior"

                bindingConfiguration="BasicHttpBinding_IService1" contract="ServiceReference1.IService1"

                name="BasicHttpBinding_IService1" />

        </client>


參考:

WCF中如何修改MaxItemsInObjectGraph的限制

WCF測試錯誤碼

MaxItemsInObjectGraph

[ASP.NET] WCF 傳輸超過 65536 的資料


其它參考:

解决进行反序列化时出错:。InnerException 消息是“反序列化对象 属于类型 System.String 时出现错误。读取 XML 数据时,超出最大字符串内容长度配额

maxReceivedMessageSize and maxBufferSize in app.config



2022年2月28日 星期一

[除錯] 無法建立 SSL/TLS 的安全通道

問題:

無法建立 SSL/TLS 的安全通道

收到來自傳輸資料流的未預期 EOF 或 0 個位元組


參考:

SecurityProtocolType 列舉

CA5386:避免將 SecurityProtocolType 值寫入程式碼


HttpWebRequest GetResponse()出現"要求已經中止: 無法建立 SSL/TLS 的安全通道"錯誤

[C#] 無法建立 SSL/TLS 的安全通道。解決方法

[VB.NET]加入HTTPS的服務參考遇到的問題

【原創】C# API 未能創建 SSL/TLS 安全通道 問題解決

要求已經中止: 無法建立 SSL/TLS 的安全通道。

HttpWebRequest GetResponse()出現"要求已經中止: 無法建立 SSL/TLS 的安全通道"錯誤

【茶包射手日記】.NET 3.5 TLS 1.2 踩雷記

.NET Framework 3.5 and TLS 1.2


解決C#呼叫有ssl憑證問題的網站出現遠端憑證是無效的錯誤問題

呼叫有ssl憑證問題的網站出現遠端憑證是無效的錯誤問題

ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;

private static bool RemoteCertificateValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)

{

    //// trust any certificate!!!

    //System.Console.WriteLine("Warning, trust any certificate");

    //return true;

            

    if (error == SslPolicyErrors.None)

    {

        return true;

    }

    var request = sender as HttpWebRequest;

    if (request != null)

    {

        var result = (request.RequestUri.Host == "11x.x.x.x" || request.RequestUri.Host == "192.16x.x.x");

        return result;

    }

    return false; 

}

CA5359: Do not disable certificate validation

AuthenticationException: Authentication failed, see inner exception. Win32Exception: 接收到的訊息超出預期或格式不正確。WebException: 要求已經中止: 無法建立 SSL/TLS 的安全通道。

System.Net.WebException: 要求已經中止: 無法建立 SSL/TLS 的安全通道 錯誤的另一種可能性2018-10-19



公開WebService:

政府資料開放平臺資料集清單

ListPriceWebService_NaturalGas

ListPriceWebService


解決:Winform .net 3.5

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;


//動態調用webservices Url

string url = "https://vipmember.tmtd.cpc.com.tw/OpenData/ListPriceWebService.asmx";


//無參數調用

object result1 = WebServiceHelper.InvokeWebService(url, "getCPCAviationFuelListPrice", null);          dataGridView1.DataSource = ((DataSet)result1).Tables[0];


2021年11月11日 星期四

[C#] 反射/反映(Reflection)物件,並判斷資料型態是否為Nullable,以利於sqlQuery時丟不同的參數值。

情況:

資料表的 [生產日期、序號] 資料型態,可為NULL,並且長度不可為零


public class tblO統計資料表

{

    public string 統計別 { get; set; }

    public DateTime? 生產日期 { get; set; }

    public int? 序號 { get; set; }

    public string 卡號 { get; set; }

}


解決:

透過 IsGenericType  、 GetGenericTypeDefinition

判斷是否為 Nullable 的泛型

而決定INSERT時,值要放 Null 還是 EmptyString/String


C#

If (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))


 var t = typeof(tblO統計資料);

var PropertyInfos = t.GetProperties(BindingFlags.Public | BindingFlags.Instance);

foreach (var PropertyInfoItem in PropertyInfos)

{

    var vv = PropertyInfoItem.PropertyType.IsGenericType && PropertyInfoItem.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>);

}


VB.NET

If type.IsGenericType AndAlso type.GetGenericTypeDefinition() Is GetType(Nullable(Of)) Then 


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

Dim mdl = Assembly.LoadFile(HttpContext.Current.Server.MapPath("~/bin/" & modelName)).GetType(modelClsName)


For Each v In mdl.GetProperties()

    If v.PropertyType.IsGenericType() AndAlso v.PropertyType.GetGenericTypeDefinition() Is GetType(Nullable(Of )) Then

        args.Add("@" & rw.Key, IIf(Not String.IsNullOrEmpty(rw.Value), rw.Value.ToString(), Nothing))

    Else

        args.Add("@" & rw.Key, rw.Value.ToString())

    End If

Next


參考:

C# Reflection: How to get the type of a Nullable<int>?

Difference between IsGenericType and IsGenericTypeDefinition


Type中的3个bool属性: IsGenericType , IsGenericTypeDefinition , IsGenericParameter

使用反射(Reflection)對物件的結構進行操作 (一)

比對型別的幾種方式

2020年7月2日 星期四

[debug] Round函數 、 四捨五入

寫Report時,由於 MS Access 、 .Net 的Round都是四捨六入(銀行家演算法) IEEE標準
如果要真正的四捨五入算法
則要使用:
Format(單位重量 x 數量 , "N2")
Round(單位重量 x 數量 , 2 , System.MidpointRounding.AwayFromZero)

範例:
原始值: (double)單位重量 x (int)數量

 一、Format(單位重量 x 數量,"N2") , Total = 48.23

 二、Round(單位重量 x 數量,2,System.MidpointRounding.AwayFromZero)  , Total = 48.22







其中要注意:
Round()函數如果傳入double型別,因為精準度不夠,會導致結果不會四捨五入。

更改如下即可:
Round(CDec(單位重量)*CDec(數量),2,System.MidpointRounding.AwayFromZero)

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

2019年1月31日 星期四

[學習] reportviewer hide export pdf excel word 禁止RDLC輸出某格式

〔winform〕 

VB.NET
Private Sub ReportViewer1_RenderingBegin(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles ReportViewer1.RenderingBegin
    Dim info As FieldInfo
    For Each extension In Me.ReportViewer1.LocalReport.ListRenderingExtensions()
        If extension.Name = "PDF" Then
            info = extension.GetType().GetField("m_isVisible", BindingFlags.Instance Or BindingFlags.NonPublic)
            info.SetValue(extension, False)
        End If
    Next
End Sub

C#
//string exportOption = "Excel";
//string exportOption = "Word";
string exportOption = "PDF";
RenderingExtension extension = reportViewer1.LocalReport.ListRenderingExtensions().ToList().Find(x => x.Name.Equals(exportOption, StringComparison.CurrentCultureIgnoreCase));
if (extension != null)
{
                System.Reflection.FieldInfo fieldInfo = extension.GetType().GetField("m_isVisible", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
                fieldInfo.SetValue(extension, false);
}

參考:
禁止ReportViewer工具栏上的导出按钮?
reportviewer禁止导出Excel按钮
ReportViewer - Hide PDF Export
ReportViewer 2010:how to hide pdf in export option in reportviewer
Hide (Disable) specific export option in ReportViewer from Export button
Hide (Disable) specific export option (Word / Excel / PDF) from Export button

2019年1月15日 星期二

[除錯] 轉換至可為Null的型別, Convert to Nullable

轉換DataTable至List<T>時,當自訂義的物件<T>包含Nullable的型別,則會引發錯誤

原本型別轉換
pro.SetValue(objT, (row[pro.Name] == DBNull.Value ? null : Convert.ChangeType(row[pro.Name], pI.PropertyType)), null);

改成
pro.SetValue(objT, (row[pro.Name] == DBNull.Value ? null : ChangeType(row[pro.Name], pI.PropertyType)), null);


        //轉換為可為 Null 的型別
        public static object ChangeType(object value, Type conversion)
        {
            var t = conversion;

            if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                if (value == null)
                {
                    return null;
                }

                t = Nullable.GetUnderlyingType(t);
            }

            return Convert.ChangeType(value, t);
        }


錯誤訊息:
Invalid cast from 'System.Int32' to 'System.Nullable`

從 'System.Decimal' 至 'System.Nullable`1[[System.Decimal, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' 的轉換無效。

參考:
Invalid cast from 'System.Int32' to 'System.Nullable`1[[System.Int32, mscorlib]]
C#将数据转换为指定类型,支持对可空类型(Nullable类)转换方法示例

我们知道在C#中,引用类型可以为null,而值类型不可以为null,就是值类型必须要有值。msdn上面的解释是值类型没有足够的空量来表示空值,它的容量只够表示适合该类型的值,没有多余的容量。而数据库中(比如sqlserver)中,任何类型的值都是可以为null的,这就给我们在往数据库中插入值带来麻烦了,比如要往数据库中的int字段中插入一个null值,而C#在2.0之前,是不可能给一个int类型的变量赋于null的。

为了解决这个问题,C#引入了Nullable类,该类为值类型赋于null值提供了支持,如果我们要为一个int类型赋于null值,那么我们就可以声明该类型为Nullable<int >,也可以直接缩写为int?,这就是我们在C#2.0后版本中看到的大量可为空的值类型声明方式。

基础基元类型的概念:
可空类型的原类型称之为该类型的基础基元类型,比如我们声明了变量int?,那么我们就称int为int?的基础基元类型。

明白了这些概念后,现在假设我们要写一个方法,该方法要支持将一个object类型的值转换为任何可能转换的类型。
该类有两个参数,值value,类型convertsionType,
如果不支持可空类型,那么该方法很好实现,如下:
public static object ChanageType(object value, Type convertsionType)
{
return Convert.ChangeType(value, convertsionType);
}


但如果convertsionType为可空类型,该方法就会报类似如下错误了:
从“System.String”到“System.Nullable`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]”的强制转换无效。

所以改写方法如下:
public static class PageBaseHelper
{
    public static object SD_ChanageType(this object value, Type convertsionType)
    {
        //判断convertsionType类型是否为泛型,因为nullable是泛型类,
        if (convertsionType.IsGenericType &&
            //判断convertsionType是否为nullable泛型类
            convertsionType.GetGenericTypeDefinition().Equals(typeof(Nullable< >)))
        {
            if (value == null || value.ToString().Length == 0)
            {
                return null;
            }

            //如果convertsionType为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换
            NullableConverter nullableConverter = new NullableConverter(convertsionType);
            //将convertsionType转换为nullable对的基础基元类型
            convertsionType = nullableConverter.UnderlyingType;
        }
        return Convert.ChangeType(value, convertsionType);
    }
}

OK,现在该方法可以适用于值对任何类型的转换了,试试吧!

[.NET]將DataTable轉成List物件
Convert DataTable to List<T>

Convert to a Type on the fly in C#.NET
C#利用反射给对象赋值
如果该属性类型是未知非泛型类型,例如 int?
property.SetValue(obj,Convert.ChangeType(value, property.PropertyType), null);//类型转换。这时简单调用 ChangeType()方法,类型会报错。

2018年9月13日 星期四

[學習][RDLC] 報表頁數 依照群組分頁 Reset Page Number in RDLC Report by group


It can be done actually, but not without adding some custom code to the report:
Shared reportGroup as String
Shared newPage  as Integer

Public Function ResetPageNumber(newGroup as String)
  If Not (reportGroup = newGroup)
    reportGroup = newGroup 
    newPage  = 1
  Else
    newPage  = newPage  + 1
  End If
  Return newPage
End Function
Then in the footer, add text box for page number and make it's value:
= Code.ResetPageNumber(ReportItems!TextBoxWithYourGroupNameOrID.Value)

參考:
https://stackoverflow.com/questions/23300494/reset-page-number-in-rdlc-report-by-group
https://www.codeproject.com/Questions/1195280/Resetting-page-number-if-group-changes-in-RDLC-rep

注意:
頁尾一次只能參考一個欄位,如需多欄位的話,可以在最內的群組做組合即可。
或者資料群已做好排序,只要按最內的群組做分頁也可以,因為會重新RESET。

2017年12月4日 星期一

【除錯】Double 資料行的預設值無法使用,而消費者尚未設定新 Double 值。


問題:
1.提供者無法決定 Double 值。例如,剛建立資料列,Double 資料行的預設值無法使用,而消費者尚未設定新 Double 值。

2.提供者無法決定 Int16 值。例如,剛建立資料列,Int16 資料行的預設值無法使用,而消費者尚未設定新 Int16 值

解決:
當你看到類似的句子時,沒有錯不要懷疑,就是你的SQL要修改。

1.造成此次問題的原因為ACCESS中,SQL將數值除以零時所導致。SQL在ACCESS可正常執行,但除以零的欄位會顯示【錯誤】,而在程式介面CRUD撈完資料要塞入DataTable時,此時便會產生如問題所述之警告文字,因而程式中斷。

只要將SQL語法判斷零的字數,並依自己的程式需求改為正確的語法即可。
例如:將會導致錯誤的零改為正一或負一即可。

2.double 轉 int 精準度問題,CInt會直接報錯誤

2015年6月10日 星期三

[除錯] DataGridView RowValidating事件, 當按Escape取消時, 不要引發該事件...

as title...

參考:
Escaping DataGridView Row creation fires RowValidating. How to avoid this?

1)
private void dataGridView1_KeyDown(object sender, KeyEventArgs e) 
     if (e.KeyCode == Keys.Escape) 
          this.dataGridView1.RowValidating -= 
               new System.Windows.Forms.DataGridViewCellCancelEventHandler(this.dataGridView1_RowValidating); 

     this.dataGridView1.RowValidating += 
          new System.Windows.Forms.DataGridViewCellCancelEventHandler(this.dataGridView1_RowValidating); 
}


2)
if (!view.IsCurrentRowDirty ) return; 


2015年2月12日 星期四

[學習] 在C#實現VB函式【IsNumeric】

【CODE】
        static bool IsNumeric(object Expression)
        {
            // Variable to collect the Return value of the TryParse method.
            bool isNum;
            // Define variable to collect out parameter of the TryParse method. If the conversion fails, the out parameter is zero.
            double retNum;
            // The TryParse method converts a string in a specified style and culture-specific format to its double-precision floating point number equivalent.
            // The TryParse method does not generate an exception if the conversion fails. If the conversion passes, True is returned. If it does not, False is returned.
            isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
            return isNum;
        }

【CODE】
        public static bool IsNum(String str)
        {
            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] < '0' || str[i] > '9')
                    return false;
            }
            return true;
        }

參考:
判断一个字符串是否全是数字的多种方法及其性能比较(C#实现)
[C#]IsNumeric 判斷是否為數值
[C#]數值驗證 IsNumeric
C# Equivalent of VB's IsNumeric()
C# IsNumeric
C#的判斷是否為數字,難道只能用Try、Catch嗎?..沒有VB.NET的IsNumeric可用嗎

2015年1月29日 星期四

[學習] MenuStrip 合併菜單

除錯:
mdiParent的MenuStrip若設定 Ctrl-X 等文字編輯快捷鍵時,當mdiChildren無MenuStrip設定...
則該視窗的 RichTextbox 會因 mdiParent 的快捷鍵設定而失效...

解決:
直接在mdiChildren設定MenuStrip並設定與mdiParent第一格相同的名稱,
並將該格enable設為false,MergeAction=Replace,MergeIndex設為要取代MenuStrip某欄的Index
無需再設定任何快捷鍵...
則RichTextbox的文字編輯快捷鍵立即復活...

參考:
【转】menustrip控件中mergeaction属性的作用
在 Windows 窗体 MenuStrip 控件中合并菜单项
合併 Windows Form MenuStrip 控制項中的功能表項目

2015年1月20日 星期二

[學習] 從一個datatable找某column的最大值

運用linq + lambda
或直接用datatable的彙總函式

e.Row.Cells("收退序號").Value = If(dgv_單據明細.Rows.Count > 1,
     tbl.Compute("max(收退序號)",
     "管理模式編號=" & cbo_管理模式編號.SelectedValue & _
     " AND 收退單號='" & txt_收退單號.Text & "'") + 1,
     1)

參考:
從查詢中建立 DataTable (LINQ to DataSet)
單一資料表查詢 (LINQ to DataSet)
DataTable: Get Max Value Using LINQ With Criteria Field (GroupBy)
How to select min and max values of a column in a datatable?
DataTable.Compute 方法

[學習] 當二個以上Combobox繫結相同來源時,若其中一個改變選項,則其它相同參考的Combobox不隨之改變....

程式:[用不同的BindingContext就好了]
        If MyUserProgInfo.frmLogin使用WebServices Then
            cbo_單據別1.DataSource = ws.ItemtblB備案手冊單據別基本資料表_GetMdl()
        Else
            cbo_單據別1.DataSource = New BLLMSSQL.BllBasicCtrlsSource().ItemtblB備案手冊單據別基本資料表
        End If
        cbo_單據別1.DisplayMember = "DisplayValue"
        cbo_單據別1.ValueMember = "單據別"

        cbo_單據別2.BindingContext = New BindingContext()
        cbo_單據別2.DataSource = cbo_單據別1.DataSource
        cbo_單據別2.DisplayMember = "DisplayValue"
        cbo_單據別2.ValueMember = "單據別"

參考:
WinForms ComboBox data binding gotcha
Multiple Combo Boxes With The Same Data Source (C#)

BindingContext 類別
关于控件使用DataBindings.Add方法进行简单绑定的问题

Bind multiple ComboBox to a single List - Issue: When I select an item, all combo boxes change

WinForm数据绑定--BindingContext
How can i bind data to a datagridview combobox column?

You could create a BindingList<> object to hold your objects and then bind that list to the three controls. Then setting the BindingContexts to different objects would let the 3 controls have different positions with a single list.
  
public partial class Form1 : Form
  {
  public Form1()
  {
    InitializeComponent();
  }
 
  private void Form1_Load(object sender, EventArgs e)
  {
    BindingList<MyObject> list = new BindingList<MyObject>();
    list.Add(new MyObject("Ramya", 43));
    list.Add(new MyObject("Manju", 43));
    list.Add(new MyObject("Gulnus", 43));
    list.Add(new MyObject("Sona", 43));
 
    dataGridView1.DataSource = list;
    comboBox1.DataSource = list;
    comboBox1.DisplayMember = "Name";
    comboBox1.ValueMember = "Name";
 
    comboBox2.DataSource = list;
    comboBox2.DisplayMember = "Name";
    comboBox2.ValueMember = "Name";
 
    comboBox1.BindingContext = new BindingContext();
    comboBox2.BindingContext = new BindingContext();
    dataGridView1.BindingContext = new BindingContext();
 
  }
  }
 
  public class MyObject
  {
  private string mName;
  private int mAge;
 
  public MyObject(string s, int i)
  {
    mName = s;
    mAge = i;
  }
  public string Name
  {
    get { return mName; }
    set { mName = value; }
  }
  public int Age
  {
    get { return mAge; }
    set { mAge = value; }
  }
  public override string ToString()
  {
    return Name;
  }
  }

2014年9月17日 星期三

2014年7月10日 星期四

[學習] 從自訂義類別中查詢 linq & lambda

說明:
主細表 Master-Detail
中幫USER自動瀘掉, Detail DGV某欄位(combobox)已存在的選項(ex: A 與 B)
當DGV AddNewRow時, 自動選出不包含A 與 B 的第一個選項(ex: C)

解決:
不知怎麼直接截取DGV當時對應於Master畫面的選項值
ex:
MasterA -> Detail A,B
MasterB -> Detail C

所以只好重新從D etail DataTable select 出來

籂選出DataRow
Dim b() As DataRow = CType(bs_tblB備案手冊號基本資料表進口項次.DataSource, DataSet).Tables(tblProductName).Select("手冊編號='" & txt_手冊編號.Text & "' AND 進口項次號=" & txt_進口項次號.Text)

將DataRow取其中一個欄位,並轉成陣列
Dim c = b.Select(Function(o) o("產品大類")).ToArray

飾選出來共有這麼多
MsgBox(CType(CType(dgv_項次產品.Columns("產品大類"), DataGridViewComboBoxColumn).DataSource, List(Of Mdl.tblBProductsType)).Where(Function(o) Not c.Contains(o.ProductsTypeID)).Count)

找出第一筆要的欄位資料
MsgBox(CType(CType(dgv_項次產品.Columns("產品大類"), DataGridViewComboBoxColumn).DataSource, List(Of Mdl.tblBProductsType)).Where(Function(o) Not c.Contains(o.ProductsTypeID))(0).ProductsTypeID)

參考:
逐步解說:使用兩個 Windows Form DataGridView 控制項建立主要/詳細表單
[學習] Master-Detail 父子表(主細表)

LINQ運算式基本構成子句
Lambda 運算式 (Visual Basic)
Visual Basic 中的 LINQ 簡介
[VB.NET]Lambda運算式
Lambda Expression for “not in”?
How to implement NOT IN clause in LINQ/LAMBDA Query expression?Explain with an example.
[C#][LINQ]動態組Where條件
How to select a field with linq on datarow
[LINQ] 查詢DataRow欄位(LINQ to DataSet)
VB.Net Linq - How to append a where clause?
How would you do a “not in” query with Linq?
Linq to Datarow, Select multiple columns as distinct?
Use LINQ to get items in one List<>, that are not in another List<>
LINQ - 在WHERE條件式中使用IN與NOT IN
LINQ to SQL 可以做到的功能
LINQ to Object - VB.NET
how to filter list in c# with lambda expression?
Filtering collections in C#

DataRow.GetChildRows 方法 (DataRelation)
比較 DataRow (LINQ to DataSet)

2014年5月14日 星期三

[學習] DataGridView 設置 Column 顯示的格式為百分比

目的:
將Column的格式設置為百分比!

法一:    
DataGridView1.DataSource = dt
DataGridView1.Columns("新增次數").Visible = False
DataGridView1.Columns("供應商成交率").DefaultCellStyle.Format = "p"
DataGridView1.Columns("集團成交率").DefaultCellStyle.Format = "p"

法二:

Private Sub DataGridView1_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
      If Me.DataGridView1.Columns(e.ColumnIndex).Name = "供應商成交率" OrElse Me.DataGridView1.Columns(e.ColumnIndex).Name = "集團成交率" Then
          If e.Value IsNot Nothing Then
              e.Value = e.Value * 100 & "%"
          End If
      End If
End Sub

結果:
(1)原始資料


(2)顯示資料







參考:
DataGridView中显示百分比
DataGridView.CellFormatting 事件
格式化 Windows Form DataGridView 控制項中的資料
[C#] 字串輸出格式
string.Format 格式參數
23654.3654          Result
N0 取整數           23654
N1 取一位數       23654.3
N2 取二位數       23654.36(若有進位就 23654.37)
以此類推
DataGridView 控制項 (Windows Form)

[ASP.NET] Gridview 欄位輸出格式 DataFormatString
http://msdn.microsoft.com/zh-tw/library/vstudio/f9x2790s(v=vs.100).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1