站內文章

顯示具有 C#-WebForm應用 標籤的文章。 顯示所有文章
顯示具有 C#-WebForm應用 標籤的文章。 顯示所有文章

2014年10月20日 星期一

gridview中以TemplateField新增button來做刪除row的動作


我的做法是用TemplateField的資料行自己抓一個button命名"刪除"
將資料庫的資料砍掉,再更新一次Gridview,網路上也有其他不同的做法
這邊分享一篇同樣是刪除動作的教學文章
http://blog.finalevil.com/2008/11/aspnetgridview03.html

本文這個方法需要建gridview的RowCommand和RowDeleting


原始檔修改

                       
                   



程式碼
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int index = Convert.ToInt32(e.CommandArgument);//取得點選的index y軸
        GridViewRow selectedRow = GridView1.Rows[index];//取得x軸
        TableCell device_lot_num = selectedRow.Cells[1];//取得批次編號欄位
        switch (e.CommandName)//取得x軸點選的button
        {
            case "Delete"://刪除
                // 連接資料庫
                SqlConnection SqlConn = new SqlConnection();
                SqlConn.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\VS20141001\\App_Data\\TPC_Transformers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
                SqlConn.Open();
                // 刪除 MaterialCollarManagement 資料表中 所選取刪除的資料(以 批次編號Collar_Number為條件 )
                SqlCommand Cmd = new SqlCommand("Delete From MaterialCollarManagement where Collar_Number = '" + device_lot_num.Text + "'", SqlConn);
                // 執行刪除指令
                Cmd.ExecuteNonQuery();
                Cmd.Dispose();
                break;
            default:
                break;
        }
    }


    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        // 重新將資料庫的資料讀到datatable並bind進去gridview
        DataTable dt3 = new DataTable();
        SqlConnection SqlConn = new SqlConnection();
        SqlConn.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\VS20141001\\App_Data\\TPC_Transformers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
        SqlConn.Open();
        SqlDataAdapter da = new SqlDataAdapter("Select ROW_NUMBER() OVER(ORDER BY Collar_Number DESC) AS Row,Collar_Number,Transformer_Amount,Switch_Amount,Apply_Date,Collar_User,Authorize_User, " +
        "Case when Authorize = 0 then '未核准' when Authorize = 1 then '核准' END AS Authorize, " +
        "Case when Depot = 0 then '出庫' when Depot = 1 then '在庫' END AS  Depot " +
        "From MaterialCollarManagement Where Authorize = '0'", SqlConn);
        da.Fill(dt3);
        GridView1.DataSource = dt3;
        GridView1.DataBind();
        SqlConn.Close();
    }

建立 .sdf 檔案


這邊會用到 System.Data.SqlServerCe
需支援 Visual Studio 2010 SP1

        
        // path = 欲建立檔案的路徑
        // 附註 這邊的路徑中 有用到 反斜線 \ 都得用兩個 反斜,否則會出現 "無法辨認的逸出序列" 的錯誤
        // 關於這個錯誤可以參考 http://msdn.microsoft.com/zh-tw/library/44ezxxy3
        string path = "D:\\Documents and Settings\\Bisger\\My Documents\\WindowsCE My Documents\\test.sdf";
        string constrpda = "DataSource=" + path;
        if (!File.Exists(path)) // 如果路徑path的檔案不存在則執行
        {
            SqlCeEngine engine = new SqlCeEngine(constrpda);
            engine.CreateDatabase();
        }

// 這邊也補上刪除檔案的指令
       File.Delete(path); 




如果出現 命名空間 'System.Data' 中沒有型別或命名空間名稱 'SqlServerCe' (您是否遺漏了組件參考?)
該組件存在 system.data.sqlserverce.dll,其路徑為
『C:\Program Files\Microsoft SQL Server Compact Edition\v3.5\Desktop\System.Data.SqlServerCe.dll』,視版本,4.0 存在
『C:\Program Files\Microsoft SQL Server Compact Edition\v4.0\Desktop\System.Data.SqlServerCe.dll』,只要將這個 DLL 加入參考就可以正常使用了。
32位元版則在『C:\Program Files (x86)\Microsoft SQL Server Compact Edition\v3.5\Desktop\System.Data.SqlServerCe.dll』與
『C:\Program Files (x86)\Microsoft SQL Server Compact Edition\v4.0\Desktop\System.Data.SqlServerCe.dll』
若找不到以上所述路徑,代表你的電腦沒有裝 SQLCE 啦!
請至 Microsoft Download Center 下載。3.5版4.0版
文章參考來源

2014年10月17日 星期五

import excel to datatable


之前在網路上查到的,臨時找不回那篇文章,只留當初找到的那個檔案
直接下載這個專案檔去試試看就知道了~
點我下載 ImportExcelData.zip

將excel資料匯入datatable中

主功能程式碼如下
            if (FileUpload1.HasFile)
            {
                string connectionstring = "";
                string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
                string fileextension = Path.GetExtension(FileUpload1.PostedFile.FileName);
                string filelocation = Server.MapPath("~/file/") + filename;
                FileUpload1.SaveAs(filelocation);
                if (fileextension == ".xlsx")
                {
                    connectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filelocation + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=2\"";
                    OleDbConnection conn = new OleDbConnection(connectionstring);
                    OleDbCommand cmd = new OleDbCommand();
                    cmd.CommandType = System.Data.CommandType.Text;
                    cmd.CommandText = "select * from [Sheet1$]";
                    cmd.Connection = conn;
                    OleDbDataAdapter oda = new OleDbDataAdapter(cmd);
                    System.Data.DataTable dt = new System.Data.DataTable();
                    oda.Fill(dt);
                    Gridview1.DataSource = dt;
                    Gridview1.DataBind();
                }
            }
            else
            {
                BtnUpload.Attributes.Add("OnClientClick", "javascript:alert('Select Excel file');");
                Gridview1.DataSource = null;
                Gridview1.DataBind();
            }
            FileUpload1.Attributes.Clear();

gridview export excel

參考書籍 微軟MVP的ASP.NET 4.5專題實務I p11-7
書上光碟有附很多範例,如果真要買這方面的書,蠻推薦這本的@@



這是使用NPOI1.2.4版來匯出EXCEL(其他版本可能不適用)
所以一開始得先抓一下NPOI的Library
點我下載 NPOI 1.2.4 Library

抓完後再專案那右鍵->加入參考


//== NPOI的宣告 ==================
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel; 
//===============================

        //== 本範例的資料來源:http://msdn.microsoft.com/zh-tw/ee818993.aspx 
        //== http://tonyqus.sinaapp.com/archives/73  (v.1.2.4版)
        HSSFWorkbook workbook = new HSSFWorkbook();
        //=======================================(v.1.2.4版)
        //== 新增試算表 Sheet名稱。使用 NPOI.SS.UserModel命名空間。
        ISheet u_sheet = (ISheet)workbook.CreateSheet("My Sheet_124");
        //=======================================
 
        //===============================================(主要功能start)
        //== 利用迴圈,把gridview的資料 一個一個 寫入 Excel各個儲存格裡面。
        for (int a = 0 ; a < GridView1.Rows.Count ; a++) // gridview的row
        {
            //**** 先建好一列(Row),才能去作格子(Cell)
            IRow u_Row = u_sheet.CreateRow(a+1);
            for (int i = 0; i < GridView1.Rows[a].Cells.Count; i++) //gridview的column
            {
               //== .CreateCell() 可設定為同一列(Row)的 [第幾個格子]
               u_Row.CreateCell(i).SetCellValue(GridView1.Rows[a].Cells[i].Text);
            }
        }
        //===============================================(主要功能end)
        MemoryStream ms = new MemoryStream();  //==需要 System.IO命名空間
        workbook.Write(ms);
        //== Excel檔名,請寫在最後面 filename的地方
        Response.AddHeader("Content-Disposition", "attachment; filename=申請書.xls");
        Response.BinaryWrite(ms.ToArray());

        //== 釋放資源
        workbook = null;   //== VB為 Nothing
        ms.Close();
        ms.Dispose();

        //== 如果要寫在 Web Server的硬碟裡面,請參閱上一個範例 NPOI_01_new_v124.aspx。
    }



// 最後面這邊補上單一欄位新增的方式

        //**** CreateRow()方法,只有這一列的「第一格子」可以這樣用。(v.1.2.4版 的新變化)
        // 每一列的第0個值
        u_sheet.CreateRow(0).CreateCell(0).SetCellValue("0000"); // 第0列 第0欄
        u_sheet.CreateRow(1).CreateCell(0).SetCellValue("1111"); // 第1列 第0欄
        //== 以下在  (v.1.2.1版,正常) 在 目前這個版本會異常
        //u_sheet.CreateRow(6).CreateCell(1).SetCellValue("6666");  // 第6列 第1欄
        //u_sheet.CreateRow(6).CreateCell(2).SetCellValue("7777");

        //== 如果要「讀取」某個格子,請用 .GetCell(index)方法

        //**********************************************************(start)
        //**** v.1.2.4版在此有很大的改變!!!請看 http://tonyqus.sinaapp.com/archives/73  
        IRow u_Row= u_sheet.CreateRow(6);    //== 先用 IRow介面,建立全新的一列。 第6列
        //== .CreateCell() 可設定為同一列(Row)的 [第幾個格子]
        u_Row.CreateCell(1).SetCellValue("6666");   // 第6列 第1欄 新增 6666
        u_Row.CreateCell(2).SetCellValue("7777");   // 第6列 第2欄 新增 7777




這邊再分享一個匯出時可以去除girdview裡面的 "& nbsp;" 以及新增第一行欄位名稱

    protected void Button1_Click(object sender, EventArgs e)
    {
        // 去除girdview裡面的 " "
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            for (int j = 0; j < GridView1.Rows[i].Cells.Count; j++)
            {
                if (GridView1.Rows[i].Cells[j].Text == " ")
                {
                    GridView1.Rows[i].Cells[j].Text = "";
                }
            }
        }
        //== 本範例的資料來源:http://msdn.microsoft.com/zh-tw/ee818993.aspx 
        //== http://tonyqus.sinaapp.com/archives/73  (v.1.2.4版)

        HSSFWorkbook workbook = new HSSFWorkbook();

        //=======================================(v.1.2.4版)
        //== 新增試算表 Sheet名稱。使用 NPOI.SS.UserModel命名空間。
        ISheet u_sheet = (ISheet)workbook.CreateSheet("My Sheet_124");
        //=======================================
   
        //===============================================(start)
        //== 利用迴圈,把資料寫入 Excel各個儲存格裡面。
        for (int a = -1 ; a < GridView1.Rows.Count ; a++) // +1個 欄位名稱的 row
        {
            //**** 先建好一列(Row),才能去作格子(Cell)
            IRow u_Row = u_sheet.CreateRow(a+1);
            if (a == -1) //第 0 列要顯示欄位名稱
            {
                // 第0列新增欄位名稱
                u_Row.CreateCell(0).SetCellValue("項目號碼"); // 第0欄
                u_Row.CreateCell(1).SetCellValue("檢修品名稱"); // 第1欄
                u_Row.CreateCell(2).SetCellValue("規格");
                u_Row.CreateCell(3).SetCellValue("數量");
                u_Row.CreateCell(4).SetCellValue("單位");
                u_Row.CreateCell(5).SetCellValue("試驗項目");
                u_Row.CreateCell(6).SetCellValue("良");
                u_Row.CreateCell(7).SetCellValue("不良");
                u_Row.CreateCell(8).SetCellValue("備註");
            }
            else
            {
                for (int i = 0; i < GridView1.Rows[a].Cells.Count; i++)
                {
                    //== .CreateCell() 可設定為同一列(Row)的 [第幾個格子]
                    u_Row.CreateCell(i).SetCellValue(GridView1.Rows[a].Cells[i].Text);
                }
            }
        }
        //===============================================(end)

        MemoryStream ms = new MemoryStream();  //==需要 System.IO命名空間
        workbook.Write(ms);
        //== Excel檔名,請寫在最後面 filename的地方
        Response.AddHeader("Content-Disposition", "attachment; filename=材料課委試報告書.xls");
        Response.BinaryWrite(ms.ToArray());

        //== 釋放資源
        workbook = null;   //== VB為 Nothing
        ms.Close();
        ms.Dispose();
        //== 如果要寫在 Web Server的硬碟裡面,請參閱上一個範例 NPOI_01_new_v124.aspx。
    }

2014年10月16日 星期四

在gridview顯示之前,判斷資料並顯示不同狀況


使用SQL的case


一開始先在gridview上的boundfield物件中,設定其datafield來源(為資料表的名稱)



//SELECT CASE ("欄位名")
//  WHEN "條件1" THEN "結果1"
//  WHEN "條件2" THEN "結果2"
//  ...
//  [ELSE "結果N"]
//  END
//FROM "表格名";

       da = new SqlDataAdapter("Select ROW_NUMBER() OVER(ORDER BY Collar_Number DESC) AS Row," +
            "Collar_Number,Transformer_Amount,Switch_Amount,Apply_Date,Collar_User,Authorize_User, " +
            "Case when Authorize = 0 then '未核准' when Authorize = 1 then '核准' END AS Authorize, " +
            "Case when Depot = 0 then '出庫' when Depot = 1 then '在庫' END AS  Depot " +
            "From MaterialCollarManagement Where Authorize = '0'", SqlConn);

// 當 Authorize = 0 會在gridview中datafield來源設定Authorize的物件上顯示 未核准
// 當 Depot = 1 會在gridview中datafield來源設定Depot的物件上顯示 在庫

SQL case 用法可以參考 http://www.1keydata.com/tw/sql/sql-case.html

隱藏gridview欄位



gridview 建一個 RowCreated

// 條件可另行設定
// 主要程式碼為 e.Row.Cells[10].Visible = false; 

    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        //如果 radiobutton 選擇了 已核准, 則隱藏 刪除欄位(第十個column)
        if (RadioButtonList1.SelectedValue == "已核准") 
        {
            e.Row.Cells[10].Visible = false; 
        }
    }


2014年10月15日 星期三

將gridview中以TemplateField新增的button變成不能點選




新增一個girdview的RowDataBound

// 這邊會將gridview1所有名為 Detial 的button變fasle ->不能點選
// 須自己加條件判斷 哪時候要 enable = true
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        Button Detial;
        for (int i = 0; i < GridView1.Rows.Count; i++) // 從第0 row 到 gridview1的最後一 row
        {
            Detial = (Button)GridView1.Rows[i].FindControl("Detial"); // 用findcontrol去抓不同row對應到的button 名為 Detial
            Detial.Enabled = false; // 將 Detial 這個button enable false
        }
        break;
    }

在gridview中以TemplateField新增button並點擊



在aspx原始檔裡面將該butoon加上
CommandName = "按鈕名稱" CommandArgument='<%# Container.DataItemIndex%>'
ex:CommandName = "Detial" CommandArgument='<%# Container.DataItemIndex%>'


                
                    
                        
                    
                


建一個 gridview的 RowCommand

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int index = Convert.ToInt32(e.CommandArgument);//取得點選的index y軸
        GridViewRow selectedRow = GridView1.Rows[index];//取得x軸
        TableCell device_item_num = selectedRow.Cells[0];//取得欄位0的數值
        switch (e.CommandName)//取得x軸點選的button
        {
            case "Detial":// 按鈕名稱 (參考原始檔)
                Session["device_item_num"] = device_item_num.Text; // Session欄位0的數值
                Response.Redirect("04_02_01_00_SearchDetial.aspx"); // 跳轉頁面
                break;
            default:
                break;
        }
    }