2014年12月30日 星期二

CRM 2011 Set Owner in JavaScript

CRM 2011 Set Owner in JavaScript



JavaScript:
function OnLoadForm()
{
    setApprovalOwner()
}
function setApprovalOwner()
{
    var setUservalue = new Array();
    setUservalue[0] = new Object();
    setUservalue[0].id = Xrm.Page.context.getUserId();
    setUservalue[0].entityType = 'systemuser';
    //setUservalue[0].name = retrievedUser.FullName;

    Xrm.Page.getAttribute("new_approvalowner").setValue(setUservalue)
}

https://crmbusiness.wordpress.com/2012/03/21/crm-2011-setting-a-user-lookup-with-the-logged-in-user-with-javascript/

CRM 2011 Set Option Set Value in JavaScript

CRM 2011 Set Option Set Value in JavaScript



JavaScript:
function OnLoadForm()
{
    ApproveQuote();
}
function ApproveQuote()
{
    control = Xrm.Page.getControl("new_approvalstatus");
    attribute = control.getAttribute();
    attribute.setValue('271770002');
}

CRM 2011 Set DateTime Value in JavaScript


CRM 2011 Set DateTime Value in JavaScript




JavaScript:
function OnLoadForm()
{
    confirmApproval();
    // OR
    confirmApproval2();
}
function confirmApproval()
{
   var currentDateTime = new Date();
   Xrm.Page.getAttribute("new_approvaldate").setValue(currentDateTime);
}
function confirmApproval2()
{
   var currentDateTime = new Date();
   control = Xrm.Page.getControl("new_approvalddate");
   attribute = control.getAttribute();
   attribute.setValue(currentDateTime);
}

CRM 2011 Set Two Options Value in JavaScript

CRM 2011 Set Two Options Value in JavaScript




JavaScript:
function OnLoadForm()
{
    isApproval();
}
function isApproval()
{
    control = Xrm.Page.getControl("new_isapproval");
    attribute = control.getAttribute();
    attribute.setValue(true);
}

CRM 2011 Get Owner ID in JavaScript

CRM 2011 Get Owner ID in JavaScript



JavaScript:
function OnLoadForm()
{
    var OwnerId = GetLookup_OwnerId();
}
function GetLookup_OwnerId()
{
   var lookup = new Array();
   lookup = Xrm.Page.getAttribute("ownerid").getValue();
   if (lookup != null) {
      var name = lookup[0].name;
       var id = lookup[0].id;
       var entityType = lookup[0].entityType;
       return id;
   }
}

CRM 2011 Get Current User ID in JavaScript

CRM 2011 Get Current User ID in JavaScript

JavaScript:
function OnLoadForm()
{
   var userId = Xrm.Page.context.getUserId();
}

Other Sample(Ref Web):
function getCurrentUserFullName() {
    var serverUrl;
    if (Xrm.Page.context.getClientUrl !== undefined) {
        serverUrl = Xrm.Page.context.getClientUrl();
    } else {
        serverUrl = Xrm.Page.context.getServerUrl();
    }
    var ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
    var userRequest = new XMLHttpRequest();
    userRequest.open("GET", ODataPath + "/SystemUserSet(guid'" + Xrm.Page.context.getUserId() + "')", false);
    userRequest.setRequestHeader("Accept", "application/json");
    userRequest.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    userRequest.send();
    if (userRequest.status === 200) {
        var retrievedUser = JSON.parse(userRequest.responseText).d;
        var userFullName = retrievedUser.FullName;
        return userFullName;
    }
    else {
        return "error";
    }
}
http://msdn.microsoft.com/en-us/library/gg334511.aspx

CRM 2011 Hide Custom Ribbon Button in JavaScript

CRM 2011 Hide Custom Ribbon Button in JavaScript

↓↓↓


JavaScript:
function OnLoadForm()
{
    HideApprovalButton();
}
function HideApprovalButton()
{
    var btnApprove=top.document.getElementById("quote|NoRelationship|Form|Mscrm.Form.quote.MainTab.Management.Approve-Large");
    var btnReject=top.document.getElementById("quote|NoRelationship|Form|Mscrm.Form.quote.MainTab.Management.Reject-Large");
    btnApprove.style.display='none';
    btnReject.style.display='none';
}

Other Sample(Ref web)
function HideRibbonControl(formName) 
{
    var saveButtonID = formName + "|NoRelationship|Form|Mscrm.Form." + formName + ".Save-Large";
    var saveandcloseButtonID = formName + "|NoRelationship|Form|Mscrm.Form." + formName + ".SaveAndClose-Large";
    var saveandnewButtonID = formName + "|NoRelationship|Form|Mscrm.Form." + formName + ".SaveandNew-Medium";
    var deactivateButtonID = formName + "|NoRelationship|Form|Mscrm.Form." + formName + ".Deactivate-Medium";
    var deleteButtonID = formName + "|NoRelationship|Form|Mscrm.Form." + formName + ".Delete-Medium";
    var approveButtonID = formName + "|NoRelationship|Form|Mscrm.Form." + formName + ".Approve-Large";

    HideARibbonButton(saveButtonID);
    HideARibbonButton(saveandcloseButtonID);
    HideARibbonButton(saveandnewButtonID);
    HideARibbonButton(deactivateButtonID);
    HideARibbonButton(deleteButtonID);
    HideARibbonButton(approveButtonID);
}
function HideARibbonButton(nameOfButton) 
{
   var btn = window.top.document.getElementById(nameOfButton);
   var intervalId = window.setInterval(function () {
       if (btn != null) {
           window.clearInterval(intervalId);
           btn.disabled = true;
           btn.style.display='none';
       }

    }, 50);
}

2014年11月12日 星期三

ASP.NET C# Call Button1_Click(呼叫Button2_Click)

ASP.NET C# Call Button1_Click(呼叫Button2_Click)

C#:
// No "sender" or event args
public void Button2_Click(object sender, EventArgs e)
{
   button1_click(null, null);
}
// Button2's the sender and event args
public void Button2_Click(object sender, EventArgs e)
{  
   Button1_Click(sender, e);
}
// Button1's the sender and Button2's event args
public void Button2_Click(object sender, EventArgs e)
{  
   Button1_Click(this.Button1, e);
}

http://stackoverflow.com/questions/2152429/how-do-i-call-an-event-method-in-c

2014年11月11日 星期二

CRM2011 Setting Default Values in Form Customization(文字欄位設定預設值)

CRM2011 Setting Default Values in Form Customization(文字欄位設定預設值)



JavaScript:
function OnLoadForm()
{
    var formType = Xrm.Page.ui.getFormType();
    if(formType == 1){   //formType 1 = Create Form
        setField_Name();
    }
}
function setField_Name()
{
    Xrm.Page.getAttribute("name").setValue("howard_lai");
    //name=Entity Name, howard_lai=your value
}

CRM2011 Setting a default value on a lookup field(Lookup欄位設定預設值)

CRM2011 Setting a default value on a lookup field(Lookup欄位設定預設值)



JavaScript:
function OnLoadForm()
{
    var formType = Xrm.Page.ui.getFormType();
    if(formType == 1){   //formType 1 = Create Form
        setLookUp_Country();
    }
}
function setLookUp_Country()
{
    var country = Xrm.Page.getAttribute("countryid");
    var value = new Array();
    value[0] = new Object();
    value[0].id = "B842D214-3A33-E411-9096-00155D01017A";  // Guid Of That Look Up
    value[0].name = "JP";                                  // Name Of That Look Up
    value[0].entityType = "country";                // Entity Name Of That Look Up
    Xrm.Page.getAttribute("countryid").setValue(value);
}

2014年9月1日 星期一

T-SQL CONVERT DateTime 常用日期格式轉換

T-SQL CONVERT DateTime 常用日期格式轉換

T-SQL:
2014-09-01 10:35:44
select CONVERT(char(19), getdate(), 120)

2014-09-01
select CONVERT(char(10), getdate(), 20)

2014/09/01
select CONVERT(char(10), getdate(), 111)

14/09/01
select CONVERT(char(8), getdate(), 11)

20140901
select CONVERT(char(8), getdate(), 112)

140901
select CONVERT(char(6), getdate(), 12)

2014.09.01
select CONVERT(char(10), getdate(), 102)

14.09.01
select CONVERT(char(8), getdate(), 2)

2014年8月28日 星期四

SQL 2008 資料加密

SQL 2008 資料加密
以下範例建立一個具有儲存加密,讀取解密的資料表

參考網址:
http://dotnetframework.blogspot.tw/2011/01/blog-post.html
http://www.dotblogs.com.tw/dc690216/archive/2009/09/10/10559.aspx


1.建立非對稱金鑰。指定name=mykey, pwd=p@ssw0rd
CREATE ASYMMETRIC KEY mykey
    WITH ALGORITHM = RSA_2048
    ENCRYPTION BY PASSWORD = 'p@ssw0rd';
GO

2.查詢第1步驟所建立的key是否成功。
select * from sys.asymmetric_keys

3.建立測試資料表

4.建立新增、更新、刪除資料表的預存程序。

USE [EIP_new]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[sp_BPM_Modify_t_BPM_Seal_type_E]

 @action_type    NCHAR(1) = '' ,
 @id    INT = 0,
 @username        NVARCHAR(50) = '',
 @uid   NVARCHAR(10) = '',
 @pwd   NVARCHAR(30) = '',
 @sort   INT = 0,
 @cdt   DateTime
AS
BEGIN

 SET NOCOUNT ON;

    --傳入資料檢核
 IF (@action_type NOT IN ('A','D','U'))
 BEGIN
  DECLARE @DBID INT;
  SET @DBID = DB_ID();
  DECLARE @DBNAME NVARCHAR(128);
  SET @DBNAME = DB_NAME();
  RAISERROR
  (N'資料庫 ID:%d, 資料庫名稱: %s。 錯誤訊息:傳入的Action_Mode,必須是 A, U, D 其中一種',
  10, -- Severity.
  1, -- State.
  @DBID, -- First substitution argument.
  @DBNAME); -- Second substitution argument.
 END
 
 --宣告加密用變數
 DECLARE
  @encryp_uid NVARCHAR(max),
  @encryp_pwd NVARCHAR(max),
  @encryp_sort NVARCHAR(max)
 
 --SET @encryp_uid = ENCRYPTBYASYMKEY(ASYMKEY_ID('mykey'),@uid)
 SET @encryp_uid = ENCRYPTBYASYMKEY(ASYMKEY_ID('mykey'),CONVERT(nvarchar(max), @uid))
 --SET @encryp_pwd = ENCRYPTBYASYMKEY(ASYMKEY_ID('mykey'),@pwd)
 SET @encryp_pwd = ENCRYPTBYASYMKEY(ASYMKEY_ID('mykey'),CONVERT(nvarchar(max), @pwd))
 SET @encryp_sort = ENCRYPTBYASYMKEY(ASYMKEY_ID('mykey'),CONVERT(NVARCHAR(10),@sort))
 
 SET @encryp_uid = ENCRYPTBYASYMKEY(ASYMKEY_ID('mykey'),CONVERT(nvarchar(max), @uid))
 
 
 --插入
 IF (@action_type = 'A')
 BEGIN
  INSERT INTO t_BPM_Seal_type_E
        (
  username ,
        [uid] ,
        pwd ,
        sort ,
        cdt
        )
        VALUES
        (          
     @username,
  @encryp_uid,
        @encryp_pwd,
        @encryp_sort,
  @cdt
        )
 END
 
 --更新
 IF (@action_type = 'U')
 BEGIN
  UPDATE t_BPM_Seal_type_E
  SET username=@username,
   [uid]=@encryp_uid,
   pwd=@encryp_pwd,
   cdt=@cdt
  WHERE id=@id
 END
 
 --刪除
 IF (@action_type = 'D')
 BEGIN
  DELETE t_BPM_Seal_type_E
  WHERE id=@id
 END
 
END
GO

5.建立檢視資料表,用來讀取被加密的資料表
CREATE VIEW [dbo].[v_BPM_Seal_type_E]
AS
SELECT     id, username, CONVERT(NVARCHAR(50), DECRYPTBYASYMKEY(ASYMKEY_ID('mykey'), uid, N'p@ssw0rd')) AS uid, CONVERT(NVARCHAR(50),
                      DECRYPTBYASYMKEY(ASYMKEY_ID('mykey'), pwd, N'p@ssw0rd')) AS pwd, CONVERT(NVARCHAR(50),
                      DECRYPTBYASYMKEY(ASYMKEY_ID('mykey'), sort, N'p@ssw0rd')) AS sort, cdt
FROM         dbo.t_BPM_Seal_type_E

6.最後查詢被加密的資料表。
上面是未解密原資料表,下面是已解密的檢視(使用第5步驟建立的檢視表)




7.直接查詢,不透過檢視表(View)
Select id,
ENCRYPTBYASYMKEY(ASYMKEY_ID('mykey'),
CONVERT(nvarchar(max), username)) as '加密'
From dbo.t_BPM_Seal_type_E
Select  id,
CONVERT(nvarchar(10), DECRYPTBYASYMKEY(ASYMKEY_ID('mykey'), uid, N'p@ssw0rd')) as '解密'
From dbo.t_BPM_Seal_type_E

2014年8月26日 星期二

ASP.NET 將網頁輸出PDF

ASP.NET PDF
將網頁物件輸出至PDF,以下使用Table為例。

1.Download the itextsharp.dll from Internet.
2.Reference of  itextsharp.dll

3.use following references of itextsharp.dll
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
4.Now the whole code of tsPDF.aspx.cs page will be as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;  

public partial class Test_tsPDF : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }

    public override void VerifyRenderingInServerForm(Control control)
    {
        //required to avoid the runtime error "  
        //Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."  
    }  

    private void ExportGridToPDF()
    {
        try
        {
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=Vithal_Wadje.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            //GridView1.RenderControl(hw);
            Table1.RenderControl(hw);
            StringReader sr = new StringReader(sw.ToString());
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();
            Response.Write(pdfDoc);
            Response.End();
            GridView1.AllowPaging = true;
            GridView1.DataBind();
        }
        catch (Exception)
        {
            
            throw;
        }
        
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        ExportGridToPDF();  
    }
}
5.Now the whole code of tsPDF.aspx page will be as follows:
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
        <asp:GridView ID="GridView1" runat="server"></asp:GridView>
        <asp:Table ID="Table1" runat="server">
            <asp:TableRow>
                <asp:TableCell>Cell 1</asp:TableCell>
                <asp:TableCell>Cell 2</asp:TableCell>
                <asp:TableCell>Cell 3</asp:TableCell>
                <asp:TableCell>Cell 4</asp:TableCell>
                <asp:TableCell>Cell 5</asp:TableCell>
                <asp:TableCell>Cell 6</asp:TableCell>
            </asp:TableRow>
        </asp:Table>
    </div>
    </form>
</body>

Reference website:
http://www.c-sharpcorner.com/UploadFile/0c1bb2/export-gridview-to-pdf/
http://www.cc.ntu.edu.tw/chinese/epaper/0015/20101220_1509.htm

2014年8月12日 星期二

ASP.NET GridView to Excel(GridView輸出到Excel)

ASP.NET GridView to Excel(GridView輸出到Excel)

C#:
protected void Page_Load(object sender, EventArgs e)
{
        DataTable dt = new DataTable();
        GridView1.DataSource = dt;
        GridView1.DataBind();

        #region HMTL Response
        Response.Clear();
        Response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>");
        Response.AddHeader("content-disposition", "attachment;filename=" + strExportFilename + ".xls");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.xls";
        //Response.Charset = "big5";  //utf-8
        Response.Charset = "utf-8";  //utf-8
        //Response.ContentEncoding = System.Text.Encoding.GetEncoding(950); //65001
        Response.ContentEncoding = System.Text.Encoding.GetEncoding(65001); //65001

        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        GridView1.RenderControl(htmlWrite); //將物件GridView1輸出
        //Table1.RenderControl(htmlWrite); //將物件Table1輸出
        Response.Write(stringWrite.ToString().Replace("<div>", "").Replace("</div>", ""));
        Response.End();
        #endregion
}

ASP.NET 型別 'GridView' 的控制項 'GridView1' 必須置於有 runat=server 的表單標記之中

ASP.NET 型別 'GridView' 的控制項 'GridView1' 必須置於有 runat=server 的表單標記之中



在.cs中加入下段即可
public override void VerifyRenderingInServerForm(Control control)
{
    //處理'GridView' 的控制項 'GridView' 必須置於有 runat=server 的表單標記之中
}

Ref
http://social.msdn.microsoft.com/Forums/zh-TW/fc860a06-bb14-40fd-bced-9d86af5d9653/gridviewexcel?forum=236

2014年8月7日 星期四

ASP.NET 取得GridView Cells下所有Label物件

ASP.NET 取得GridView Cells下所有Label物件

C#:
 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType != DataControlRowType.DataRow) // 非資料行, 離開
                    return;

                //單筆, 取得指定名稱Label物件, 若Text="n/a", 將Text改為空白
                Label lblGvptz_zoom = e.Row.FindControl("lblGvptz_zoom") as Label;
                if (lblGvptz_zoom.Text.Equals("n/a"))
                    lblGvptz_zoom.Text = "";

                //多筆迴圈, 取得Row下所以Cells中的Label物件, 若Text="n/a", 將Text改為空白
                foreach (TableCell cl in e.Row.Cells)
                {
                    foreach (object ctrl in cl.Controls)
                    {
                        if (ctrl is System.Web.UI.WebControls.Label) //判斷ctrl是否為Label物件
                        {
                            Label lblctrl = (Label)ctrl;
                            if (lblctrl.Text.Equals("n/a"))
                                lblctrl.Text = "";
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

2014年8月5日 星期二

T-SQL Cannot create a row of size 9440 which is greater than the allowable maximum row size of 8060

T-SQL Cannot create a row of size 9440 which is greater than the allowable maximum row size of 8060

StoredProcedure寫了一段PIVOT時出現的錯誤訊息
錯誤原因是其中有一個欄位長度超過8060,解決方法將原來nvarchar(max)改為==>nvarchar(4000)即可

下段StoredProcedure其中text1使用了nvarchar(max)


將text1改為nvarchar(4000)即可






2014年8月4日 星期一

T-SQL Stored Procedure使用條件式 IN

T-SQL Stored Procedure使用條件式 IN

How to pass string parameter with `IN` operator in stored procedure

(1)T-SQL (sp_ATS_ComparisonPIVOT) 主要預存程序
傳入參數:@model = N'A1234,B1234'
CREATE PROCEDURE [dbo].[sp_ATS_ComparisonPIVOT]
 
 @model       nvarchar(max)   
AS
 declare @ColumnGroup   nvarchar(max),
   @PivotSQL    nvarchar(max)
BEGIN
 
 SET NOCOUNT ON;
 
 select  @ColumnGroup = COALESCE(@ColumnGroup + ',' ,'' ) + QUOTENAME(model)
 FROM t_ATS_spec
 --請看下一行範例
 where model in (Select data From dbo.fn_slip_str(@model,','))
 GROUP BY QUOTENAME(model)
 select @ColumnGroup
 
 SELECT @PivotSQL = N'
 SELECT *
 FROM  (SELECT technicalspecification,name,model,text1 FROM t_ATS_spec) AS SourceTable
 PIVOT
 (max(text1)
 FOR
 model  IN (' + @ColumnGroup + N')
 ) AS PivotTable'
 exec(@PivotSQL)

END



(2)T-SQL(Function fn_slip_str)搭配字串分割程序使用
Create Function fn_slip_str( @InStr nvarchar(2000) , @s_char nvarchar(1) )
Returns @tb Table ( sno int , data nvarchar(100) )
As
Begin
    /*依據傳入字元進行字串分割,回傳Table*/
    /*
    Declare @InStr nvarchar(2000) , @s_char nvarchar(1);
    Set @InStr = '字串一,字串2,字串3,字串4';
    Set @s_char = ',';*/

    Set @InStr = @s_char + @InStr + @s_char;
    Declare @p1 Int , @p2 Int , @data nvarchar(100) , @sno int;
    Set @p1 = -1 ; Set @p2 = -1 ; Set @data = '' ; Set @sno = 0;
    While ( 0 Not In (@P1,@P2) ) Begin
  Set @p1 = CharIndex(@s_char,@InStr,@p1+1);
  Set @p2 = CharIndex(@s_char,@InStr,@p1+1);
  If ( 0 In (@p1,@p2) )
      Break;
  Set @data = SubString(@InStr,@p1+1,@p2-@p1-1);
  if ( @data <> '' ) Begin
      Set @sno = @sno +1;
      Insert Into @tb ( sno , data ) Values ( @sno , @data )
  End
    End
    Return
End

(3)執行結果:
Select * From dbo.fn_slip_str('字串一,字串2,字串3,字串4',',');

Ref WebSite
http://www.dotblogs.com.tw/rachen/archive/2008/05/23/4110.aspx

T-SQL字串分割

T-SQL字串分割

T-SQL code(backup):
Create Function fn_slip_str( @InStr nvarchar(2000) , @s_char nvarchar(1) )
Returns @tb Table ( sno int , data nvarchar(100) )
As
Begin
    /*依據傳入字元進行字串分割,回傳Table*/
    /*
    Declare @InStr nvarchar(2000) , @s_char nvarchar(1);
    Set @InStr = '字串一,字串2,字串3,字串4';
    Set @s_char = ',';*/

    Set @InStr = @s_char + @InStr + @s_char;
    Declare @p1 Int , @p2 Int , @data nvarchar(100) , @sno int;
    Set @p1 = -1 ; Set @p2 = -1 ; Set @data = '' ; Set @sno = 0;
    While ( 0 Not In (@P1,@P2) ) Begin
  Set @p1 = CharIndex(@s_char,@InStr,@p1+1);
  Set @p2 = CharIndex(@s_char,@InStr,@p1+1);
  If ( 0 In (@p1,@p2) )
      Break;
  Set @data = SubString(@InStr,@p1+1,@p2-@p1-1);
  if ( @data <> '' ) Begin
      Set @sno = @sno +1;
      Insert Into @tb ( sno , data ) Values ( @sno , @data )
  End
    End
    Return
End

執行結果:
Select * From dbo.fn_slip_str('字串一,字串2,字串3,字串4',',');

下段程式原始來源請參考下列網址(如有侵權請告知):
http://www.dotblogs.com.tw/rachen/archive/2008/05/23/4110.aspx

2014年7月30日 星期三

RDLC Invalid column

RDLC Invalid column

開發一支新的RDLC Report後,移至新主機上出現Invalid column的訊息,
最後原來是在新主機上的資料庫忘記開欄位


2014年7月21日 星期一

ASP.NET DataTable轉成Excel實體檔案

ASP.NET DataTable轉成Excel實體檔案


C#:
    protected void Button1_Click(object sender, EventArgs e)
    {
        #region 建立虛擬表格
        DataTable dt = new DataTable();
        DataColumn column;
        column = new DataColumn();
        column.DataType = Type.GetType("System.String");
        column.ColumnName = "company_name";
        dt.Columns.Add(column);
        column = new DataColumn();
        column.DataType = Type.GetType("System.String");
        column.ColumnName = "tel";
        dt.Columns.Add(column);
        column = new DataColumn();
        column.DataType = Type.GetType("System.String");
        column.ColumnName = "fax";
        dt.Columns.Add(column);
        column = new DataColumn();
        column.DataType = Type.GetType("System.String");
        column.ColumnName = "email";
        dt.Columns.Add(column);
        column = new DataColumn();
        column.DataType = Type.GetType("System.String");
        column.ColumnName = "contact";
        dt.Columns.Add(column);
        column = new DataColumn();
        column.DataType = Type.GetType("System.String");
        column.ColumnName = "company_address";
        dt.Columns.Add(column);
        #endregion

        //輸出
        ExcelFileStream(dt, @"D:\", "abc.xls");
    }
    private void ExcelFileStream(DataTable dt, string savepath, string filename)
    {
        try
        {
            Stream fs = RenderDataTableToExcel(dt);
            SaveStreamToFile(savepath + filename, fs);
        }
        catch (Exception)
        {
            throw;
        }
    }
    public static Stream RenderDataTableToExcel(DataTable srcTable)
    {
        try
        {
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet();
            HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0);
            foreach (DataColumn column in srcTable.Columns)
            {
                headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
            }
            int rowIndex = 1;
            foreach (DataRow row in srcTable.Rows)
            {
                HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex);
                foreach (DataColumn column in srcTable.Columns)
                {
                    dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                }
                rowIndex++;
            }

            MemoryStream stream = new MemoryStream();
            workbook.Write(stream);
            stream.Flush();
            stream.Position = 0;
            sheet = null;
            headerRow = null;
            workbook = null;
            return stream;
        }
        catch (Exception)
        {

            throw;
        }

    }
    public void SaveStreamToFile(string fileFullPath, Stream stream)
    {
        try
        {
            if (stream.Length == 0) return;

            // Create a FileStream object to write a stream to a file
            using (FileStream fileStream = System.IO.File.Create(fileFullPath, (int)stream.Length))
            {
                // Fill the bytes[] array with the stream data
                byte[] bytesInStream = new byte[stream.Length];
                stream.Read(bytesInStream, 0, (int)bytesInStream.Length);

                // Use FileStream object to write to the specified file
                fileStream.Write(bytesInStream, 0, bytesInStream.Length);
            }
        }
        catch (Exception)
        {
            throw;
        }

    }

2014年7月17日 星期四

ASP.NET 呼叫CMD執行批次檔BAT

ASP.NET 呼叫CMD執行批次檔BAT

C#:
    private void go()
    {
        try
        {
            // Get the full file path
            string strFilePath = @"C:\inetpub\wwwroot\ga\copyphone.bat";

            // Create the ProcessInfo object
            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("cmd.exe");
            psi.UseShellExecute = false;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardInput = true;
            psi.RedirectStandardError = true;
            psi.WorkingDirectory = @"C:\inetpub\wwwroot\ga\";

            // Start the process
            System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);


            // Open the batch file for reading
            System.IO.StreamReader strm = new System.IO.StreamReader(strFilePath, System.Text.Encoding.GetEncoding(950));
            //System.IO.StreamReader strm = System.IO.File.OpenText(strFilePath);
            //strm.CurrentEncoding.GetEncoder = System.Text.Encoding.GetEncoding(950);
            //strm = System.IO.File.OpenText(strFilePath);
            Response.Write(strm.CurrentEncoding.ToString());

            // Attach the output for reading
            System.IO.StreamReader sOut = proc.StandardOutput;

            // Attach the in for writing
            System.IO.StreamWriter sIn = proc.StandardInput;


            // Write each line of the batch file to standard input
            while (strm.Peek() != -1)
            {
                sIn.WriteLine(strm.ReadLine());
            }

            strm.Close();

            // Exit CMD.EXE
            string stEchoFmt = "# {0} run successfully. Exiting";

            sIn.WriteLine(String.Format(stEchoFmt, strFilePath));
            sIn.WriteLine("EXIT");

            // Close the process
            proc.Close();

            // Read the sOut to a string.
            string results = sOut.ReadToEnd().Trim();


            // Close the io Streams;
            sIn.Close();
            sOut.Close();

            string fmtStdOut = "{0}";
            this.Response.Write(String.Format(fmtStdOut,results.Replace(System.Environment.NewLine, "
"))); } catch (Exception ex) { throw ex; } }

2014年7月2日 星期三

ASP.NET UseSubmitBehavior用法

ASP.NET UseSubmitBehavior用法

以下是我是目前的理解:有錯誤請指正

(1)一般用法:按Button1後執行的動作是Submit,執行Button1_Click,此時預設值UseSubmitBehavior="true"
<asp:Button ID="Button1" runat="server" Text="Submit"  OnClick="Button1_Click" />

(2)加入UseSubmitBehavior="false"用法:按Button1後執行的動作是一般的Button,執行Button1_Click
<asp:Button ID="Button1" runat="server" Text="Submit"  OnClick="Button1_Click" UseSubmitBehavior="false" />

(3)加入UseSubmitBehavior="false"和OnClientClick用法:按Button1後執行的動作是一般的Button,先執行OnClientClick後再執行Button1_Click
<asp:Button ID="Button1" runat="server" Text="Submit"  OnClick="Button1_Click" UseSubmitBehavior="false" OnClientClick="this.disabled=true;this.value='Saveing...';" />

(4)OnClientClick用法:按Button1後執行的動作是一般的Button,先執行OnClientClick後再執行Button1_Click,如果在OnClientClick事件發生後卻得到false的訊息,就不會發生PostBack
<asp:Button ID="Button1" runat="server" Text="Submit"  OnClick="Button1_Click" OnClientClick="return confirm('Are you sure you want to submit this form?');" />

2014年6月9日 星期一

ASP.NET Gridview Edit 按兩次才能編輯解決方法

ASP.NET Gridview Edit 按兩次才能編輯解決方法

C#:
 protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            try
            {
                //1.重新綁定
                GridView1.EditIndex = e.NewEditIndex;
                //2.重新DataBind
                Gvlistitem.DataSource = dt;
                GridView1.DataBind();
            }
            catch (Exception)
            {
                throw;
            }
        }

2014年6月4日 星期三

ASP.NET Foreach RadioButton

ASP.NET Foreach RadioButton



HTML:
<asp:Panel ID="pan_RadioButton1" runat="server">
<asp:RadioButton ID="rbtempty" runat="server" GroupName="ProjectType" Text="Empty project without any defaults." /><br />
<asp:RadioButton ID="rbtcopy" runat="server" GroupName="ProjectType" Text="Copy an existing project." />&nbsp;
<asp:DropDownList ID="ddlcopymodel" runat="server" Width="100"></asp:DropDownList>
</asp:Panel>
<asp:Button ID="btnSave" runat="server" Text="Save" Width="100" OnClientClick="return confirm('Do you really want to save?');" OnClick="btnSave_Click" />
<asp:Button ID="btnprojecttypecancel" runat="server" Text="Cancel" Width="100" />

C#:
protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string r_id = "";
                string r_value = "";
             
                foreach (Control ctrl in pan_RadioButton1.Controls)//pan_RadioButton1這是Panel物件,取出Panel中所有物件
                {
                    if (ctrl.GetType().Name == "RadioButton") //判斷物件是否為RadioButton
                    {
                        RadioButton rbt = ctrl as RadioButton; //將ctrl建立成RadioButton物件
                        if (rbt.Checked) //判斷RadioButton是否被選取
                        {
                            r_id = rbt.ID.ToString();
                            r_value = rbt.Text;
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

2014年5月27日 星期二

ASP.NET How to give the postbackurl in gridview link button

ASP.NET How to give the postbackurl in gridview link button


HTML:
<asp:GridView ID="GridView1" runat="server"  CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateColumns="false">
                        <Columns>
                            <asp:TemplateField HeaderText="Model">
                                <ItemStyle HorizontalAlign="Center" Width="200" />
                                <ItemTemplate>
                                    <asp:LinkButton ID="lnkGvmodel" runat="server" Text='<%# Bind("model") %>' CommandArgument='<%# Eval("model") %>' PostBackUrl='<%# String.Format("~/ats/model.aspx?model={0}", Eval("model"))%>'></asp:LinkButton>
                                </ItemTemplate>
                            </asp:TemplateField>
                            </Columns>
</asp:GridView>

2014年5月24日 星期六

ASP.NET Combobox Sample

ASP.NET Combobox Sample
DropDownList TextBox


HTML:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <style type="text/css">
        .t1
        {
            width:200px;
            position:absolute;
        }
        .d1
        {
            width:217px;
            height:22px;
            clip:rect(auto auto auto 200px);
            position:absolute;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server" CssClass="t1" ></asp:TextBox>
        <asp:DropDownList ID="DropDownList1" runat="server" CssClass="d1" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"  AutoPostBack="true">
            <asp:ListItem Text="a" Value="1"></asp:ListItem>
            <asp:ListItem Text="b" Value="2"></asp:ListItem>
            <asp:ListItem Text="c" Value="3"></asp:ListItem>
        </asp:DropDownList>
    </div>
    </form>
</body>
</html>

C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Test_tsCombobox : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        TextBox1.Text = DropDownList1.SelectedItem.Text;
    }
}

2014年5月21日 星期三

ASP.NET GridView EditItemTemplate變換不同物件

ASP.NET GridView EditItemTemplate變換不同物件

在RowEditing時依據資料來源顯示不同的物件,下列以TextBox程DropDownList為例:
hfGvnetobject=>存放來自資料庫記載的物件別(TextBox or DropDownList)
hfGvnetobject.Value 等於TextBox時,顯示TextBox隱藏DropDownList物件
hfGvnetobject.Value 等於DropDownList時,顯示DropDownList隱藏TextBox物件
以下範例:

HTML:
<asp:TemplateField HeaderText="value">
    <ItemStyle HorizontalAlign="Center" Width="170" />
    <EditItemTemplate>
        <asp:HiddenField ID="hfGvnetobject" runat="server" Value='<%# Bind("netobject") %>' />
        <asp:TextBox ID="tbxGvvalue1" runat="server" Text='<%# Bind("value1") %>'></asp:TextBox>
        <asp:DropDownList ID="ddlGvvalue1" runat="server"></asp:DropDownList>
    </EditItemTemplate>
    <ItemTemplate>
        <asp:Label ID="lblGvvalue1" runat="server" Text='<%# Eval("value1") %>'></asp:Label>
    </ItemTemplate>
</asp:TemplateField>

C#:
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType != DataControlRowType.DataRow) // 非資料行, 離開
            return;
        if (e.Row.RowState == DataControlRowState.Edit || ((int)e.Row.RowState) == 5) //判斷為Edit模式,因偶數列無法判斷故加入((int)e.Row.RowState)==5的條件
        {
            HiddenField hfGvnetobject = e.Row.FindControl("hfGvnetobject") as HiddenField; //取得EditItemTemplate下的hfGvnetobject Value存放物件型態
            TextBox tbxGvvalue1 = e.Row.FindControl("tbxGvvalue1") as TextBox; //取得EditItemTemplate下的TextBox物件
            DropDownList ddlGvvalue1 = (DropDownList)e.Row.FindControl("ddlGvvalue1"); //取得EditItemTemplate下的DropDownList物件
            if (hfGvnetobject.Value == "TextBox") //假設物件型態等於TextBox, 顯示TextBox物件, 隱藏DropDownList物件
            {
                tbxGvvalue1.Visible = true;
                ddlGvvalue1.Visible = false;
            }
            if (hfGvnetobject.Value == "DropDownList") //假設物件型態等於DropDownList, 顯示DropDownList物件, 隱藏TextBox物件
            {
                tbxGvvalue1.Visible = false;
                ddlGvvalue1.Visible = true;
            }
        }
    }

2014年5月13日 星期二

ASP.NET取得觸發Postback的Button

ASP.NET取得觸發Postback的Button

HTML:
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" Width="100px" UseSubmitBehavior="false" />

C#:
protected void Page_Load(object sender, EventArgs e)
{
    if (this.Request.Form["__EVENTTARGET"] == btnSubmit.UniqueID)
    {
            btnSubmit.Enabled = false;
    }
}

ASP.NET防止等待回應中重複按Submit

ASP.NET防止等待回應中重複按Submit

Submit送出時改變Button Enable狀態,讓使用者無法再按Submit

HTML:
<asp:button id="btnSubmit" onclick="btnSubmit_Click" runat="server" text="Submit" usesubmitbehavior="false" width="100px">
</asp:button>

C#:
protected void Page_Load(object sender, EventArgs e)
{
    this.btnSubmit.Attributes.Add("onclick", ClientScript.GetPostBackEventReference(btnSubmit, "click") + ";this.disabled=true; this.value='Saveing...';");
}

2014年5月12日 星期一

ASP.NET 防止回上一頁重複新增

ASP.NET 防止回上一頁重複新增

----------------------------------------------------------------------------------------------------
.cs

protected void Page_Load(object sender, EventArgs e)
 {
      Response.Cache.SetCacheability(HttpCacheability.NoCache);
      Response.Cache.SetNoStore();            
      Response.Cache.SetExpires(DateTime.MinValue);
 }

 protected void Button1_Click(object sender, EventArgs e)
 {
       Save();
       Response.Redirect("success.aspx");
       //Server.Transfer("success.aspx", true);
 }

 private void Save()
 { }

2014年5月8日 星期四

ASP.NET Confirm dialog

ASP.NET Confirm dialog












Sample 1: ASP.NET
----------------------------------------------------------------------------------------------------
.aspx

<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" OnClientClick="return confirm('Do you really want to save?');" />


Sample 2: ASP.NET Call JAVASCRIPT Function
----------------------------------------------------------------------------------------------------
.aspx

<asp:Button runat="server" ID="btnUserDelete" Text="Delete" OnClick="BtnUserDelete_Click" OnClientClick="if ( ! UserDeleteConfirmation()) return false;"  />

<script type="text/javascript">
        function UserDeleteConfirmation() {
            return confirm("Are you sure you want to delete this user?");
        }
</script>


Sample 3: C#
----------------------------------------------------------------------------------------------------
.cs

protected void Page_Load(object sender, System.EventArgs e)
{
     if (!IsPostBack)
     {
         btnSave.Attributes["Onclick"] = "return confirm('Do you really want to save?');";        
     }
}

2014年3月20日 星期四

您必須加入參考至組件 'App_Code.xevmfwa_, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null

您必須加入參考至組件 'App_Code.xevmfwa_, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null

<configuration>
<system.web>
<compilation debug="true" batch="false"> <!--此行加入Web.config解決-->
</compilation>
</system.web>
</configuration>

2014年3月13日 星期四

DataTable Select RowFilter 資料複製到另一個DATATABLE

DataTable Select RowFilter 資料複製到另一個DATATABLE

//Create DataTable
                DataTable dt = new DataTable();
                DataColumn column;
                DataRow row;

                // Create column.
                column = new DataColumn();
                column.DataType = Type.GetType("System.Int16");
                column.ColumnName = "ID";
                dt.Columns.Add(column);

                // Create new DataRow objects and add to DataTable.
                for (int i = 1; i <= 10; i++)
                {
                    row = dt.NewRow();
                    row["ID"] = i.ToString();
                    dt.Rows.Add(row);
                }

                //RowFilter exsample1
                dt.DefaultView.RowFilter = "ID=1";
                //RowFilter exsample2
                dt.DefaultView.RowFilter = "ID>1";
             
                //sort
                dt.DefaultView.Sort = "id desc";

                //RowFilter Copy New Table
                DataTable dtNew = dt.Clone();
                foreach(DataRow dr in dt.Select("ID > 5","ID"))
           {
               dtNew.ImportRow(dr);
           }
               //Copy all row to new Table
              DataTable dtNew = dt.Clone();
            foreach (DataRow dr in dt.Rows)
            {
                dtNew.ImportRow(dr);
            }

2014年3月3日 星期一

DataTable刪除欄位Column, 新增查詢刪除DataRow

How remove columns from ADO.NET DataTable?

DataTable remove column
dt.Columns.Remove(string name)
dt.Columns.Remove("id")
//or
dt.Columns.Remove(int index)
dt.Columns.Remove(0)

Create New DataTable
DataTable dt = new DataTable();

Create New Column
DataColumn column;
column = new DataColumn();
column.DataType = Type.GetType("System.String");
column.ColumnName = "ID";
dt.Columns.Add(column);

Create new DataRow objects and add to DataTable.
DataRow row;
for (int i = 1; i <=10; i++)
{
   row = dt.NewRow();
   row["ID"]= i.ToString();
   dt.Rows.Add(row);
}

Select Row
row = dt.Select("ID='1'")[0];

Delete Row
row = dt.Select("ID='2'")[0];
row.Delete();

AcceptChanges
dt.AcceptChanges();

2014年3月2日 星期日

SQL 多筆Insert新增資料

SQL 多筆Insert新增資料
使用簡易方法=>傳入DataTable後自動組合成SQL指令後寫入DataBase

//1.取得空的DataTable
DataTable dt = GetEmptyTable("Table1");
//2.資料放入DataTable
DataRow dr = dt.NewRow();
dr["id"] = "1";
dr["no"] = "A001";
dt.Rows.Add(dr);

//3.DataTable存入資料庫
MultiInsert(dt, "Table1");


//Function
        /// <summary>
        /// 多筆新增資料
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public static int MultiInsert(DataTable dt, string tableName)
        {
            try
            {
                int count = dt.Rows.Count;
                string ConnectionString = ConfigurationManager.ConnectionStrings[BPM.BPM_ConnStr].ToString();
                using (SqlConnection conn = new SqlConnection(ConnectionString))
                {
                    conn.Open();
                    //組合SQL  Insert String
                    string mysql = InsertString_Collect(tableName, dt);
                    SqlTransaction mytrans = conn.BeginTransaction();
                    //逐筆檢驗 逐筆新增
                    foreach (DataRow dr in dt.Rows)
                    {
                        //檢驗比對資料內容是否正確
                        //如c2 ==aa then c4=false...等
                        if (1 == 1)
                        {
                            using (SqlCommand cmd = new SqlCommand(mysql, conn))
                            {
                                cmd.Transaction = mytrans;
                                foreach (DataColumn col in dt.Columns)
                                {
                                    cmd.Parameters.AddWithValue("@" + col.ColumnName, dr[col.ColumnName]);
                                }
                                cmd.ExecuteNonQuery();
                            }
                        }
                    }
                    mytrans.Commit();
                    return count;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 組出SQL Insert String
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string InsertString_Collect(string tableName, DataTable dt)
        {
            try
            {
                string sql = "INSERT INTO " + tableName + "({p}) VALUES ({v})";
                string p = string.Empty;
                string v = string.Empty;
                foreach (DataColumn col in dt.Columns)
                {
                    p += col.ColumnName.ToString() + ",";
                    v += "@" + col.ColumnName.ToString() + ",";
                }
                p = p.Substring(0, int.Parse(p.Length.ToString()) - 1);
                v = v.Substring(0, int.Parse(v.Length.ToString()) - 1);
                sql = sql.Replace("{p}", p);
                sql = sql.Replace("{v}", v);
                return sql;
            }
            catch (Exception)
            {
                throw;
            }
        }
  /// <summary>
        /// 取得空的Table
        /// </summary>
        /// <param name="tableName">Database Table Name</param>
        /// <returns>DataTable</returns>
        public static DataTable GetEmptyTable(string tableName)
        {
            DataTable dt = new DataTable();
            try
            {
                SqlConnection cn = new SqlConnection();
                SqlCommand cmd = new SqlCommand();
                SqlDataAdapter da = new SqlDataAdapter();
                DataSet ds;
                string sql = string.Empty;
                string sqlwhere = string.Empty;
                string sqlsort = string.Empty;
                #region Execute SQL
                cn.ConnectionString = ConfigurationManager.ConnectionStrings[BPM.BPM_ConnStr].ToString();
                cmd.Connection = cn;
                cmd.CommandText = "SELECT * FROM " + tableName + " WHERE 1=0";
                cn.Open();
                da.SelectCommand = cmd;
                sql = da.SelectCommand.CommandText;
                ds = new DataSet();
                da.Fill(ds, "dt");
                dt = ds.Tables["dt"];
                cn.Close();
                #endregion Execute SQL
            }
            catch (Exception)
            {
                //throw;
            }
            return dt;
        }

2014年1月17日 星期五

SortedList c#.net

SortedList c#.net

c#

//for 
        SortedList mySL1 = new SortedList();
        mySL1.Add("1", "Book");
        mySL1.Add("2", "Pen");
        mySL1.Add("3", "Other");
        for (int i = 0; i < mySL1.Count; i++)
        {
            Response.Write(string.Format("{0} - {1},", mySL1.GetByIndex(i).ToString(), mySL1.GetKey(i).ToString())); //Book - 1,Pen - 2,Other - 3,
            //Add to DropDownList
            DropDownList1.Items.Add(new ListItem(mySL1.GetByIndex(i).ToString(), mySL1.GetKey(i).ToString()));
        }
// foreach
        SortedList<int, string> mySL2 = new SortedList<int, string>();
        mySL2.Add(1, "Book");
        mySL2.Add(2, "Pen");
        mySL2.Add(3, "Other");
        foreach (var pair in mySL2)
        {
            Response.Write(string.Format("{0} - {1},", pair.Value.ToString(), pair.Key.ToString())); //Book - 1,Pen - 2,Other - 3,
            //Add to DropDownList
            DropDownList2.Items.Add(new ListItem(pair.Value.ToString(), pair.Key.ToString()));
        }

        SortedList<string, string> mySL3 = new SortedList<string, string>();
        mySL3.Add("1", "Book");
        mySL3.Add("2", "Pen");
        mySL3.Add("3", "Other");
        foreach (KeyValuePair<string, string> condition in mySL3)
        {
            Response.Write(string.Format("{0} - {1},", condition.Value, condition.Key)); //Book - 1,Pen - 2,Other - 3,
            //Add to DropDownList
            DropDownList3.Items.Add(new ListItem(condition.Value, condition.Key));
        }

        SortedList<string, string> mySL4= new SortedList<string, string>();
        mySL4.Add("1", "Book");
        mySL4.Add("2", "Pen");
        mySL4.Add("3", "Other");
        foreach (string myKey in mySL4.Keys)
        {
            Response.Write(string.Format("Key={0},", myKey)); //Key=1,Key=2,Key=3,
            //display TextBox
            TextBox1.Text += myKey;
        }
        foreach (string myValue in mySL4.Values)
        {
            Response.Write(string.Format("Value={0},", myValue)); //Value=Book,Value=Pen,Value=Other,
            //display TextBox
            TextBox1.Text += myValue;
        }

        //Contains
        bool contains1 = mySL1.ContainsKey("1");
        Response.Write(contains1.ToString()); //True
        //Bind CheckBox
        CheckBox1.Checked = contains1;

        //index
        int index1 = mySL1.IndexOfKey("2");
        Response.Write(index1.ToString()); //1
        Label1.Text = index1.ToString();
        int index2 = mySL1.IndexOfValue("Pen");
        Response.Write(index2.ToString()); //1
        Label2.Text = index2.ToString();

        //SetByIndex
        mySL1.SetByIndex(0, "Paper");
        Response.Write((string)mySL1.GetKey(1).ToString()); //2
        Response.Write((string)mySL1.GetByIndex(0)); //Paper
        //Label3.Text = (string)mySL1.GetKey(1);
        Label3.Text = (string)mySL1.GetByIndex(0);

        //Remove
        mySL1.Remove("2");
        Response.Write(mySL1.Count.ToString()); // 2
        Label4.Text = mySL1.Count.ToString();

2014年1月2日 星期四

GridView FindControl

GridView FindControl

c#
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    Button btnGV = e.Row.FindControl("btnGVCancelOrder") as Button;
                    CheckBox ckb = e.Row.Cells[16].Controls[0] as CheckBox;
                    CheckBox ckb2 = e.Row.Cells[17].Controls[0] as CheckBox;
                    HiddenField hif = e.Row.FindControl("hifGVedt") as HiddenField;
                }
         }