> For the complete documentation index, see [llms.txt](https://johch3n611u.gitbook.io/c50108/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://johch3n611u.gitbook.io/c50108/ju-li-cheng-bei/201903/2019-0325-tmd.md).

# 2019/0325/TMD\&Asp.net上傳圖片/產生QRCode

## TMD案例

### 視覺化的關聯圖

#### 關係實體 一個課程 有 多個測驗 ，有的課程沒有考試 但有考試一定有課程

編碼規則系統設計師會標註

nvarchar 變動長度

測驗種類 遞移相依問題 但這裡依照圖施工不考慮

實體本身就有pk就不用pfk所以使用fk 不可被識別的多對1

學生 多對多於 測驗 具有 明細

![](https://1902678905-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVJQfuBXyvHwCd1Nadk%2F-LamH6zKcrXtZ2fiBn9i%2F-LamKAwLUFHP5CuOd5KJ%2Fimage.png?alt=media\&token=b6ee4e19-21a3-45fb-a77a-e357b623b078)

#### 多質屬性 轉資料表原則 要獨立一張資料表 自為一實體

要有一個自己的pk 但通常不太據原生意義 ( 流水號

![](https://1902678905-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVJQfuBXyvHwCd1Nadk%2F-LamH6zKcrXtZ2fiBn9i%2F-LamOTxoWpjA3ay3ItEy%2Fimage.png?alt=media\&token=c21b7d09-33a7-417c-b7a0-dfd9adf515f8)

但這個pk是因為學生跟地址為1對多 但不曉得學生會填幾筆資料

![](https://1902678905-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVJQfuBXyvHwCd1Nadk%2F-LamH6zKcrXtZ2fiBn9i%2F-LamOlARMDR1EnodprlZ%2Fimage.png?alt=media\&token=f8c099ef-a852-455a-9dc6-4e6d5d3afb15)

組合鍵

#### 弱實體 與 強實體差別 在於 弱實體依附強實體 ( 弱實體本身沒有pk 強消失弱也消失

![](https://1902678905-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVJQfuBXyvHwCd1Nadk%2F-LamH6zKcrXtZ2fiBn9i%2F-LamPipETL1WnyKTPwo2%2Fimage.png?alt=media\&token=307ddde8-5a61-4a3b-b9cb-75c8d7e6b45e)

TMD轉為圖檔

![](https://1902678905-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVJQfuBXyvHwCd1Nadk%2F-LamH6zKcrXtZ2fiBn9i%2F-LamRatTUk79KR6fARzC%2Fimage.png?alt=media\&token=eeb3b22b-79ab-4b77-8824-820a3a9b18f5)

![](https://1902678905-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVJQfuBXyvHwCd1Nadk%2F-LamH6zKcrXtZ2fiBn9i%2F-LamRnqSq_i3DTgPo8e6%2Fexport.jpg?alt=media\&token=c1d7f063-0aa4-4f83-832a-64c23e8e08c8)

### sql ddl scrip

![](https://1902678905-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVJQfuBXyvHwCd1Nadk%2F-LamH6zKcrXtZ2fiBn9i%2F-LamS4NddMFBMzgnfURU%2Fimage.png?alt=media\&token=8909f7b4-78b1-4691-81dd-39c4c0f9bba7)

![](https://1902678905-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVJQfuBXyvHwCd1Nadk%2F-LamH6zKcrXtZ2fiBn9i%2F-LamSLC-NHd0VERVrqQr%2Fimage.png?alt=media\&token=d1a40ace-a8bd-444e-a0ab-ace051c8c253)

create database hw5&#x20;

go&#x20;

use hw5&#x20;

go

```
/*
Created		2019/3/21
Modified		2019/3/25
Project		
Model			
Company		
Author		
Version		
Database		MS SQL 2005 
*/


Create table [Students]
(
	[學號] Char(4) NOT NULL,
	[姓名] Nvarchar(20) NOT NULL,
	[性別] Bit NOT NULL,
	[電話] Varchar(16) NULL,
	[生日] Datetime NULL,
Primary Key ([學號])
) 
go

Create table [課程]
(
	[課程編號] Char(1) NOT NULL,
	[名稱] Nvarchar(20) NULL,
	[學分] Integer NOT NULL,
Primary Key ([課程編號])
) 
go

Create table [班級]
(
	[學號] Char(4) NOT NULL,
	[教授編號] Char(4) NOT NULL,
	[課程編號] Char(1) NOT NULL,
	[上課時間] Datetime NOT NULL,
	[教室] Varchar(8) NOT NULL,
Primary Key ([學號],[教授編號],[課程編號])
) 
go

Create table [教授]
(
	[教授編號] Char(4) NOT NULL,
	[科系] Varchar(5) NOT NULL,
	[職稱] Nvarchar(4) NOT NULL,
	[身份證字號] Char(10) NULL,
Primary Key ([教授編號])
) 
go

Create table [員工]
(
	[身份證字號] Char(10) NOT NULL,
	[姓名] Nvarchar(20) NOT NULL,
	[電話] Varchar(16) NULL,
	[城市] Nvarchar(4) NOT NULL,
	[街道] Nvarchar(10) NOT NULL,
	[薪水] Money NOT NULL,
	[保險] Money NOT NULL,
	[扣稅] Money NOT NULL,
Primary Key ([身份證字號])
) 
go

Create table [測驗]
(
	[測驗編號] Char(4) NOT NULL,
	[名稱] Nvarchar(20) NOT NULL,
	[種類] Char(1) NULL,
	[課程編號] Char(1) NULL,
Primary Key ([測驗編號])
) 
go

Create table [結果]
(
	[測驗編號] Char(4) NOT NULL,
	[學號] Char(4) NOT NULL,
	[成績] Integer NOT NULL,
	[日期] Datetime NOT NULL,
Primary Key ([測驗編號],[學號])
) 
go

Create table [地址]
(
	[地址流水號] Bigint Identity NOT NULL,
	[地址] Nvarchar(30) NOT NULL,
	[學號] Char(4) NOT NULL,
Primary Key ([地址流水號],[學號])
) 
go

Create table [家長]
(
	[姓名] Nvarchar(20) NOT NULL,
	[關係] Nvarchar(4) NULL,
	[學號] Char(4) NOT NULL,
Primary Key ([姓名],[學號])
) 
go


Alter table [班級] add  foreign key([學號]) references [Students] ([學號])  on update no action on delete no action 
go
Alter table [結果] add  foreign key([學號]) references [Students] ([學號])  on update no action on delete no action 
go
Alter table [地址] add  foreign key([學號]) references [Students] ([學號])  on update no action on delete no action 
go
Alter table [家長] add  foreign key([學號]) references [Students] ([學號])  on update no action on delete no action 
go
Alter table [班級] add  foreign key([課程編號]) references [課程] ([課程編號])  on update no action on delete no action 
go
Alter table [測驗] add  foreign key([課程編號]) references [課程] ([課程編號])  on update no action on delete no action 
go
Alter table [班級] add  foreign key([教授編號]) references [教授] ([教授編號])  on update no action on delete no action 
go
Alter table [教授] add  foreign key([身份證字號]) references [員工] ([身份證字號])  on update no action on delete no action 
go
Alter table [結果] add  foreign key([測驗編號]) references [測驗] ([測驗編號])  on update no action on delete no action 
go


Set quoted_identifier on
go


Set quoted_identifier off
go



```

### SQL Server資料庫圖表

![](https://1902678905-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVJQfuBXyvHwCd1Nadk%2F-LamH6zKcrXtZ2fiBn9i%2F-LamU0s0h2lccB4Zz5lb%2Fimage.png?alt=media\&token=a903dfbd-cdac-40a3-a262-4f8350bbfe7c)

## SQL 物件 預存程序 Stored Procedure

TSQL 涉及資料操作等等的 將程式寫好 等需要時再執行

資料庫資料操作與定譯 ，&#x20;

select 的程序能存成view 就類似預存程序

但不是所有程序都可以存成view&#x20;

### 建立

create Procedure 程序名稱

可簡寫  Proc

as begin 程序內容 end

![](https://1902678905-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVJQfuBXyvHwCd1Nadk%2F-LamgM5IgCBjz0iOSlpM%2F-Lamj7gx5LjJCgCcorUr%2Fimage.png?alt=media\&token=31f1ff90-3a9f-47f1-ae61-22a83a17c019)

```
--預存程序Stored Procedure
--建立
create Proc 學生選課總筆數
as
begin
	select 班級.教授編號,員工.姓名,教授.科系,教授.職稱,班級.學號,學生.姓名,學生.性別, 
	班級.課程編號,課程.名稱,課程.學分,班級.上課時間,班級.教室
	from 班級 
	inner join 學生 on 班級.學號=學生.學號 
	inner join 課程 on 班級.課程編號=課程.課程編號
	inner join 教授 on 班級.教授編號=教授.教授編號
	inner join 員工 on 教授.身份證字號=員工.身份證字號
	order by 學生.學號

	print '共有'+cast(@@rowcount as varchar)+'筆選課資料!!'
end
```

### 使用

```
--執行預存程序
execute 學生選課總筆數
--簡寫
exec 學生選課總筆數
```

exec 如果後面是一整串字串後面可以當作命令執行

```
--再談execute
declare @tablename varchar(30)
set @tablename='學生'
exec('select * from '+@tablename)
--------------------------------------
declare @procname varchar(30)
set @procname='學生選課明細'

exec @procname
```

功能會有括弧可傳遞參數 那預存程序要如何傳遞參數呢?

### 傳遞參數

#### 創建

as 前定義名稱 資料型態

```
--有參數的預存程序
create proc 學生查詢
	@name varchar(12)
as
begin

	select * from 學生
	where 姓名 like '%'+  @name+ '%'
end
```

#### 使用

```
exec 學生查詢 @name='張'
exec 學生查詢 '張'
```

## asp.net gridview 串 預存程序

具有隱藏資訊的特點

![](https://1902678905-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVJQfuBXyvHwCd1Nadk%2F-LamgM5IgCBjz0iOSlpM%2F-LamuoOneYMs5dj91rEj%2Fimage.png?alt=media\&token=a0c13508-46d1-44be-9790-a3794e8cb358)

![](https://1902678905-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVJQfuBXyvHwCd1Nadk%2F-LamgM5IgCBjz0iOSlpM%2F-LamusdjPKwh1OfFkoVF%2Fimage.png?alt=media\&token=d72b1115-54dd-4232-9310-c8d937ed24a6)

![](https://1902678905-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVJQfuBXyvHwCd1Nadk%2F-LamgM5IgCBjz0iOSlpM%2F-LamuxFPl4BlwSkB-9dm%2Fimage.png?alt=media\&token=f64e8cd3-4527-4b28-84e1-73f69d768bae)

![](https://1902678905-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVJQfuBXyvHwCd1Nadk%2F-LamgM5IgCBjz0iOSlpM%2F-Lamv-Mu3I4hieNJnh8W%2Fimage.png?alt=media\&token=5184c95b-d1af-4a17-8aa1-b8af296e102f)

![](https://1902678905-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVJQfuBXyvHwCd1Nadk%2F-LamgM5IgCBjz0iOSlpM%2F-Lamv3U6sQvl6DFzYTUg%2Fimage.png?alt=media\&token=0b923e18-dfbb-4a56-98c5-8a7f682b13cd)

![](https://1902678905-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVJQfuBXyvHwCd1Nadk%2F-LamgM5IgCBjz0iOSlpM%2F-Lamv6xd4z9SgMXPPDO5%2Fimage.png?alt=media\&token=d0d04c84-e73d-4c21-ab97-c211e7c7a4b3)

![](https://1902678905-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVJQfuBXyvHwCd1Nadk%2F-LamgM5IgCBjz0iOSlpM%2F-LamvAj3Keg3SUO4U944%2Fimage.png?alt=media\&token=59a719ea-c027-495f-9e20-da0b00125954)

![](https://1902678905-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVJQfuBXyvHwCd1Nadk%2F-LamgM5IgCBjz0iOSlpM%2F-LamvDtTQEivNnKVEwjB%2Fimage.png?alt=media\&token=28423f9e-b476-4555-a0db-385cbb9e9d69)

![](https://1902678905-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVJQfuBXyvHwCd1Nadk%2F-LamgM5IgCBjz0iOSlpM%2F-LamvH3t-tybH6oEEUgR%2Fimage.png?alt=media\&token=ccc34a10-b99a-4ee0-bc07-60827fe33c8c)

![](https://1902678905-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVJQfuBXyvHwCd1Nadk%2F-LamgM5IgCBjz0iOSlpM%2F-LamvKQ0jSix7iPXwmNv%2Fimage.png?alt=media\&token=6b3db86a-7155-4f80-a917-d762c7a0358a)

```
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:教務系統ConnectionString %>" 
SelectCommand="學生選課明細" SelectCommandType="StoredProcedure"></asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"></asp:GridView>
```

#### 傳參數 1.設置輸入框 2.確認參數資料型態

```
 輸入姓名關鍵字：<asp:TextBox ID="txtName" runat="server"></asp:TextBox><asp:Button ID="Button1" runat="server" Text="查詢" />

<asp:SqlDataSource ID="SqlDataSource2" runat="server" 
ConnectionString="<%$ ConnectionStrings:教務系統ConnectionString %>" 
SelectCommand="學生查詢" SelectCommandType="StoredProcedure">

<SelectParameters>
<asp:ControlParameter Name="name" ControlID="txtName" Type="String" />
</SelectParameters>


</asp:SqlDataSource>

<asp:GridView ID="GridView2" runat="server" DataSourceID="SqlDataSource2"></asp:GridView>
```

## datalist

唯讀畫面->編輯畫面

按下發送->回寫資料庫

### 更新圖片

### 1.必須秀原圖在畫面上&#x20;

```
    Product_Img:
                    <img src='ProductsImg/s<%# Eval("Product_Img") %>' />
```

### 2.上傳圖片功能 ( 接收資料具有高度危險性 ( 判斷限制假設有驗證器 ( 上傳沒成功

控制項 fileupload

後端鑄造物件用於抓更新值

先在後端判斷前端控制器是否有抓到東西 判斷是否有上傳檔案

監看式可以看檔名等等 也可用於除錯

做限制判斷圖檔 ( 判斷副檔名是不準的 (對方可以把病毒附檔為jpg

contentlength 檔案大小

contenttype 檔案類型

\| | 或

呼叫方法 saveas 路徑+img.filename原主檔名+副檔名 ( 寫邏輯判斷副檔名 )

但今天不是要用原檔名而是利用pk當作檔名這樣才能夠讓資料庫後續可以回傳

mapping邏輯路徑對應相對路徑 呼叫物件來用

server.mappath 去找伺服器絕對路徑

```

        protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if(e.CommandName=="Edit")
            {
                DataList1.EditItemIndex = e.Item.ItemIndex;
                DataBind();

                int index = e.Item.ItemIndex;
                string status = ((Label)DataList1.Items[index].FindControl("lblProduct_Status")).Text;
                RadioButtonList rbl = (RadioButtonList)DataList1.Items[index].FindControl("rblProduct_Status");
             
                if (status == "True")
                {
                    rbl.Items[0].Selected = true;
                }
                else
                    rbl.Items[1].Selected = true;

            }
            else if (e.CommandName == "Cancel")
            {
                DataList1.EditItemIndex = -1;
                DataBind();

            }
```

\*問題是照片大小版面呢? (實務上通常是修改到完整大小才可更新

分別using 可以少寫一些

將一張圖鑄造成image物件&#x20;

抓客戶端檔案路徑轉到參數中

讓客戶端檔案能夠轉到物件中

抓客戶端檔案格式轉至物件中

重新畫一張大圖 360\*360

{% embed url="<https://docs.microsoft.com/zh-tw/dotnet/api/system.drawing.bitmap?view=netframework-4.7.2>" %}

圖形驗證 QRcod都是用bitmap

```
  //上傳新的產品圖檔
            FileUpload img=(FileUpload)e.Item.FindControl("fulProductsImg");
            Label proID = (Label)e.Item.FindControl("Product_IDLabel");

            if (img.FileName!="")
            {
                System.Drawing.Image g = System.Drawing.Image.FromFile(img.PostedFile.FileName);
                ImageFormat imgformat = g.RawFormat;
                Bitmap newImg = new Bitmap(g,360,360);
                Bitmap newSImg = new Bitmap(g, 120, 120);


                if (img.PostedFile.ContentType == "image/jpeg")
                {
                    newImg.Save(Server.MapPath("/ProductsImg/" + proID.Text + ".jpg"));
                    newSImg.Save(Server.MapPath("/ProductsImg/s" + proID.Text + ".jpg"));
                    //img.SaveAs(Server.MapPath("/ProductsImg/" + proID.Text + ".jpg"));
                }
                else if (img.PostedFile.ContentType == "image/png")
                {
                    newImg.Save(Server.MapPath("/ProductsImg/" + proID.Text + ".png"));
                    newSImg.Save(Server.MapPath("/ProductsImg/s" + proID.Text + ".png"));
                    //img.SaveAs(Server.MapPath("/ProductsImg/" + proID.Text + ".png"));
                }

            }
```

###

### 3.按下更新按鈕後，回寫資料庫複寫 ( 複寫失敗

commandname重要=update

確認有無重新整理 ( post back

屬性 OnUpdateCommand 功能名稱

後端 將所有需要回寫的資料 鑄造物件 ( 包含索引直 pk ) 用於抓更新\值

前端 UpdateCommand 設置

讀取後端參數設置  ( 包含索引直 pk

將參數餵給後端變數 並寫入資料庫  ( 包含索引直 pk

並轉為唯讀程式

#### 前端

```
<div>
            <asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1" 
                RepeatColumns="3" CellSpacing="20" RepeatDirection="Horizontal"
                 OnItemCommand="DataList1_ItemCommand"
                  OnUpdateCommand="DataList1_UpdateCommand"
                >
     
                  
                  <ItemTemplate>
                    <div style="text-align:center">
                        <asp:Button ID="Button1" runat="server" Text="編輯資料" CommandName="Edit" />
                        <%--<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Select"> <%# Eval("Product_id") %></asp:LinkButton>--%>
                        <br />

                        <img src='ProductsImg/s<%# Eval("Product_Img") %>' />
                        <br />
                        <asp:Label ID="Label2" runat="server" Font-Names="微軟正黑體" Font-Bold="true" Font-Size="14pt" Text='<%# Eval("Product_Name") %>' />
                        <br />
                        原價：
                        <asp:Label ID="Label1" runat="server" Text='<%# Eval("Product_Price","{0:C0}") %>' ForeColor="#999999" CssClass="line_through" />
                        <br />
                        特價：
                        <asp:Label ID="Label3" runat="server" Text='<%# Eval("Product_Price2","{0:C0}") %>' ForeColor="#ff0066" Font-Names="Arial Black" Font-Size="18pt" />
                    </div>
                </ItemTemplate>

            <EditItemTemplate>
                <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Update">更新</asp:LinkButton>
                <asp:LinkButton ID="LinkButton2" runat="server" CommandName="Cancel">取消</asp:LinkButton>
                <br />
                <asp:Label ID="lblProduct_Status" runat="server" Text='<%# Eval("Product_Status") %>'></asp:Label>
           
                    Product_ID:
                    <asp:Label ID="Product_IDLabel" runat="server" Text='<%# Eval("Product_ID") %>' />
                    <br />
                    Product_Name:
                  
                <asp:TextBox ID="txtProduct_Name" runat="server" Text='<%# Eval("Product_Name") %>' Width="200"></asp:TextBox>
                    <br />
                    Product_Img:
                    <img src='ProductsImg/s<%# Eval("Product_Img") %>' /><br />
                    <asp:FileUpload ID="fulProductsImg" runat="server" />
                    <br />
                    Product_Price:
                 
                <asp:TextBox ID="txtProduct_Price" runat="server" Text='<%# Eval("Product_Price","{0:0}") %>' Width="100"></asp:TextBox>
                    <br />
                    Product_price2:
          
                <asp:TextBox ID="txtProduct_Price2" runat="server" Text='<%# Eval("Product_Price2","{0:0}") %>' Width="100"></asp:TextBox>
                    <br />
                    Product_Intro:
              
                <asp:TextBox ID="txtProduct_Intro" runat="server" TextMode="MultiLine" Text='<%# Eval("Product_Intro") %>' Width="200" Height="100"></asp:TextBox>
                    <br />
                    Product_Status:
              
                <asp:RadioButtonList ID="rblProduct_Status" runat="server" RepeatDirection="Horizontal">
                    <asp:ListItem Text="上架" Value="1"></asp:ListItem>
                    <asp:ListItem Text="下架" Value="0"></asp:ListItem>
                </asp:RadioButtonList>
                    <br />

            </EditItemTemplate>
                  
            </asp:DataList>
             <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                ConnectionString="<%$ ConnectionStrings:MySystemConnectionString1 %>" 
                SelectCommand="SELECT * FROM [Products]"
                  UpdateCommand="update Products set Product_Name=@Product_Name, Product_Price=@Product_Price, 
                 Product_Price2=@Product_Price2, Product_Intro=@Product_Intro, Product_Status=@Product_Status where Product_ID=@Product_ID"
                 >
                    <UpdateParameters>
                        <asp:Parameter Name="Product_Name" Type="String" />
                        <asp:Parameter Name="Product_Price" Type="Int32" />
                        <asp:Parameter Name="Product_Price2" Type="Int32" />
                        <asp:Parameter Name="Product_Intro" Type="String" />
                        <asp:Parameter Name="Product_Status" Type="Int16" />
                        <asp:Parameter Name="Product_ID" Type="String" />
                    </UpdateParameters>



             </asp:SqlDataSource>
        </div>
```

#### 後端

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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

        }

        protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if(e.CommandName=="Edit")
            {
                DataList1.EditItemIndex = e.Item.ItemIndex;
                DataBind();

                int index = e.Item.ItemIndex;
                string status = ((Label)DataList1.Items[index].FindControl("lblProduct_Status")).Text;
                RadioButtonList rbl = (RadioButtonList)DataList1.Items[index].FindControl("rblProduct_Status");
             
                if (status == "True")
                {
                    rbl.Items[0].Selected = true;
                }
                else
                    rbl.Items[1].Selected = true;

            }
            else if (e.CommandName == "Cancel")
            {
                DataList1.EditItemIndex = -1;
                DataBind();

            }
          
        }

        protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e)
        {
            //上傳新的產品圖檔

            //資料回寫資料庫
            TextBox name =(TextBox)e.Item.FindControl("txtProduct_Name");
            TextBox price = (TextBox)e.Item.FindControl("txtProduct_Price");
            TextBox price2 = (TextBox)e.Item.FindControl("txtProduct_Price2");
            TextBox intro = (TextBox)e.Item.FindControl("txtProduct_Intro");
            RadioButtonList status = (RadioButtonList)e.Item.FindControl("rblProduct_Status");

            Label proID=(Label)e.Item.FindControl("Product_IDLabel");

            SqlDataSource1.UpdateParameters["Product_Name"].DefaultValue = name.Text;
            SqlDataSource1.UpdateParameters["Product_Price"].DefaultValue = price.Text;
            SqlDataSource1.UpdateParameters["Product_Price2"].DefaultValue = price2.Text;
            SqlDataSource1.UpdateParameters["Product_Intro"].DefaultValue = intro.Text;
            SqlDataSource1.UpdateParameters["Product_Status"].DefaultValue = status.SelectedValue;
            SqlDataSource1.UpdateParameters["Product_ID"].DefaultValue = proID.Text;

            SqlDataSource1.Update();

            DataList1.EditItemIndex = -1;
            DataBind();

        }
    }
}
```

### 4. 取消案扭 ( 編輯狀態轉為唯讀狀態

commandname重要=Cancel

確認有無重新整理 ( post back

```
if(e.CommandName=="Edit")
            {
                DataList1.EditItemIndex = e.Item.ItemIndex;
                DataBind();

                int index = e.Item.ItemIndex;
                string status = ((Label)DataList1.Items[index].FindControl("lblProduct_Status")).Text;
                RadioButtonList rbl = (RadioButtonList)DataList1.Items[index].FindControl("rblProduct_Status");
             
                if (status == "True")
                {
                    rbl.Items[0].Selected = true;
                }
                else
                    rbl.Items[1].Selected = true;

            }
            else if (e.CommandName == "Cancel")
            {
                DataList1.EditItemIndex = -1;
                DataBind();

            }
```

### 5. chrome 執行只會抓到伺服器端檔名 不會抓到伺服器端路徑

直接存這個上傳檔案存到某個暫存資料夾 (保持原檔名與副檔名

這樣後端就能用server上的路徑做判斷

```
//上傳新的產品圖檔
            FileUpload img=(FileUpload)e.Item.FindControl("fulProductsImg");
            Label proID = (Label)e.Item.FindControl("Product_IDLabel");

            if (img.FileName!="")
            {
                img.SaveAs(Server.MapPath("/tmpImage/temp.jpg"));
                img.Dispose();

                //System.Drawing.Image g = System.Drawing.Image.FromFile(img.PostedFile.FileName);
                System.Drawing.Image g = System.Drawing.Image.FromFile(Server.MapPath("/tmpImage/temp.jpg"));
                ImageFormat imgformat = g.RawFormat;
                Bitmap newImg = new Bitmap(g,360,360);
                Bitmap newSImg = new Bitmap(g, 120, 120);


                if (img.PostedFile.ContentType == "image/jpeg")
                {
                    newImg.Save(Server.MapPath("/ProductsImg/" + proID.Text + ".jpg"));
                    newSImg.Save(Server.MapPath("/ProductsImg/s" + proID.Text + ".jpg"));
                    //img.SaveAs(Server.MapPath("/ProductsImg/" + proID.Text + ".jpg"));
                }
                else if (img.PostedFile.ContentType == "image/png")
                {
                    newImg.Save(Server.MapPath("/ProductsImg/" + proID.Text + ".png"));
                    newSImg.Save(Server.MapPath("/ProductsImg/s" + proID.Text + ".png"));
                    //img.SaveAs(Server.MapPath("/ProductsImg/" + proID.Text + ".png"));
                }

            }
```

怕同時一堆人處理 可以將暫存檔案名稱亂數處理 ( 上面沒用

### 6.網頁上catch

必須將catch釋放出來 不然圖跟上傳都會報錯

```
 img.Dispose();
```

釋放物件使用

#### 實務上會有兩頁 一頁為更新頁 一頁為預覽頁

( 最後有點聽不清楚 如果不懂這邊可以重聽

f5?

## QRcode

### 產生

![](https://1902678905-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVJQfuBXyvHwCd1Nadk%2F-LanomoIzbN90rAw_DQp%2F-LansZsGxVhWQCKDDm2d%2Fimage.png?alt=media\&token=6b588161-552c-4d75-914b-b7db00e168e0)

messagingtoolkit.qrcode

![](https://1902678905-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVJQfuBXyvHwCd1Nadk%2F-LanomoIzbN90rAw_DQp%2F-LantmfB8nkJ2S22div-%2Fimage.png?alt=media\&token=d123079e-fcdf-4a1c-863a-5d1aa076b248)

id 為自己打的亂碼&#x20;

打物件名稱選擇正確位置自動using

![](https://1902678905-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LVJQfuBXyvHwCd1Nadk%2F-LanomoIzbN90rAw_DQp%2F-Lanuz-RopVGKRpstTQj%2Fimage.png?alt=media\&token=65e6f619-082b-4834-b729-7fa36acadf8d)

graphics 也是圖形介面

```
 public partial class _29QR_Code : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            QRCodeEncoder encoder = new QRCodeEncoder();
            encoder.QRCodeVersion = 3;
            encoder.QRCodeScale = 20;

            string ProductID = "ufkjud8979302ikld";

            Bitmap img = encoder.Encode(ProductID);

            img.Save(Server.MapPath("/QR_Code/MyCdoe.jpg"), ImageFormat.Jpeg);

            Image1.ImageUrl = "/QR_Code/MyCdoe.jpg";
        }
    }
```

qrcode有芬版本

```
 encoder.QRCodeVersion = 3;
```

延展性

```
   encoder.QRCodeScale = 20;
```

### 相同名字不同物件就會有模玲兩可產生必須寫完整類別名稱

### gridview 加上 qrcode 檔案第21個&#x20;

前端

```
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="21GridView_BoundField.aspx.cs" Inherits="ASPnet._21GridView_BoundField" %>

<!DOCTYPE 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>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" />
</head>
<body>
    <form id="form1" runat="server">
        <div class="container">
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MySystemConnectionString1 %>" SelectCommand="SELECT * FROM [Products]"></asp:SqlDataSource>
            <div class="table-responsive">
            <asp:GridView GridLines="None" CssClass="table table-hover" ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
                <Columns>
                    <asp:BoundField DataField="Product_ID" HeaderText="Product_ID" SortExpression="Product_ID" />
                    <asp:BoundField DataField="Product_Name" HeaderText="Product_Name" SortExpression="Product_Name" />
                  <%--  <asp:BoundField DataField="Product_Img" HeaderText="Product_Img" SortExpression="Product_Img" />--%>
                    <asp:ImageField DataImageUrlField="Product_Img" DataImageUrlFormatString="~\ProductsImg\s{0}"></asp:ImageField>
                    <asp:BoundField DataField="Product_Price" DataFormatString="{0:C0}" HeaderText="Product_Price" SortExpression="Product_Price" />
                    <asp:BoundField DataField="Product_price2" DataFormatString="{0:C0}" HeaderText="Product_price2" SortExpression="Product_price2" />
                    <%--<asp:BoundField DataField="Product_Intro" HeaderText="Product_Intro" SortExpression="Product_Intro" />--%>
                    <asp:TemplateField HeaderText="Product_Intro" SortExpression="Product_Intro">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Product_Intro") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label1" runat="server" Text='<%# Eval("Product_Intro").ToString().Replace("\n","<br>") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:CheckBoxField DataField="Product_Status" HeaderText="Product_Status" SortExpression="Product_Status" />

                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:Image runat="server" ID="Image1"></asp:Image>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
            </div>
        </div>
    </form>
</body>
</html>
```

後端

```
using MessagingToolkit.QRCode.Codec;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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

        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {

            if (e.Row.RowIndex != -1)
            {
                QRCodeEncoder encoder = new QRCodeEncoder();


                string ProductID = e.Row.Cells[0].Text;

                Bitmap img = encoder.Encode(ProductID);

                img.Save(Server.MapPath("/QR_Code/"+ ProductID+".jpg"), ImageFormat.Jpeg);

                ((System.Web.UI.WebControls.Image)e.Row.Cells[7].FindControl("Image1")).ImageUrl = "/QR_Code/" + ProductID + ".jpg";
            }
        }
    }
}
```

## ado.net明日 正規用法 不是 datasorse
