日期: 2023.11.02 星期二

  1. 建立資料庫

    1. 伺服器總管視窗若沒出現時: 執行檢視 > 伺服器總管
      20231109134222
    2. 選擇左下視窗上的伺服器總管後然後選擇項目: 伺服器下的資料連接後,
      滑鼠右鍵選擇建立新的 SQL Server 資料庫
      20231109170039

      • 伺服器名稱: (localdb)mssqllocaldb
      • 登入伺服器: 使用 Windows 驗證
      • 新資料庫名稱: im
        20231109170843
        20231109174513
  2. 建立資料表

    1. 資料表上,按下滑鼠右鍵,選擇加入新的資料表
      20231109142712

      名稱 資料型別 允許 Null 預設值
      PID varchar(50) Not Null
      PNAME varchar(50) Not Null
      PRICE int Not Null
    2. 切換到頁籤: T-SQL,將 [Table] 命名成 [PRODUCT],然後執行 更新
      20231109195322
    3. 按下 更新資料庫
      20231109195435
    4. 回到伺服器總管按下 更新,就可以看到資料表 PRODUCT
      20231109195748
  3. 新增資料
    選擇資料表 PRODUCT 後,點擊滑鼠右側,選擇顯示資料表資料,然後在出現視窗上開始編輯與新增資料
    20231109200013

    PID PNAME PRICE
    P01 Monitor 1200
    P02 Case 3900
    P03 CPU 12000
    P04 Power 3000

    20231109151554

    打完一筆資料庫管理系統自動將這筆資料寫入資料庫,可以按下左上角確認內容,刪除可以顯取該筆後,點擊滑鼠右鍵後選擇刪除

  4. 開始建立新專案: 檔案 > 新增 > 專案
    20231031072102
    20231031072236
    20231109152125
    20231031150345
  5. 於專案項目上,滑鼠右鍵選擇加入 Web 表單
    20231103143257
    指定項目的名稱: WebForm1表單項目名稱
    20231109055139
  6. WebForm1 上,滑鼠右鍵,選擇設計工具檢視,進入設計界面
    20231109055556

  7. 案例一: WebForm1 網頁打開執行時就將能到資料庫把資料表 PRODUCT 撈出來放於 ListBox 控制項上
    在控制項上顯示 產品名稱,當按下該名稱項就會顯示該 產品價格

    1. 設計 UI 介面
      • 加入控制項 ListBox1
    2. 產生 PageLoad 事件方法

      protected void Page_Load(object sender, EventArgs e)
      {  //還沒 PostBack
         if (!this.IsPostBack)
         {
            //建立連線字串
            //@ 避免遇到特殊字元,例如 
            string strcon = @"Data Source=(localdb)mssqllocaldb;Initial Catalog=im;Integrated Security=True;Pooling=False";
            //要與 MSSQL 連線的話,要使用對應 ADO.NET 的套件,所以需要 SqlClient 套件
            //所以需先引入 System.Data.SqlClient;
            SqlConnection sqlcon = new SqlConnection(strcon);
            //連接資料庫
            sqlcon.Open();
            //產生 SQL 命令物件
            SqlCommand sqlcmd = new SqlCommand();
            //連線時要透過哪一個連線字串來連接
            sqlcmd.Connection = sqlcon;
      
            //建立 SQL 語句,要告訴資料庫做什麼: 查詢產品名稱與價錢
            sqlcmd.CommandText = "select PNAME, PRICE from product ";
            //要求資料庫系統執行並且將結果回傳封裝成 SQLDataReader 物件的型式
            SqlDataReader sqldr = sqlcmd.ExecuteReader();
            //執行一次 SqlDataReader.Reader() 方法會讀出一筆資料,有成功會回傳 True
            //取出 n 筆資料
            while( sqldr.Read()){
              //準備 ListItem
              ListItem aaa = new ListItem(); //這一行不能寫在外面變成全域事件,這樣取出的值都相同,因為指向同一位址
              aaa.Text = sqldr.GetString(0); //欄位 PName
              aaa.Value = sqldr.GetInt32(1).ToString(); //欄位 Price
              //放到 ListBox
              ListBox1.Items.Add(aaa);
            }
         }
      }
    3. 測試結果
      20231109211533

      連線字串

      20231109154414
      20231109154531

      引入類別 System.Data.SqlClient

  8. 案例二: 新增一個功能,即是按下 ListBox 裡面的項目內容(產品名稱),就會帶出 產品價格

    1. UI 部分:
      Label1.Text = ""
      20231109214000
    2. 因為要按下去列出產品價格,需在伺服器端作,既然要在伺服端執行(才會知道選了哪一項目),就必須 Postback,而且須將價格放在 Label1 內。
    3. 在控制項 ListBox 上設定屬性: AutoPostBack = True
      20231109214134
    4. 雙擊控制項 ListBox 來建立事件 ListBox1_SelectedIndexChang 方法(這事件被觸發時機在於項目改變時)

      protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
      {
          //Label1.Text = ListBox1.SelectedItem; //找到選擇到的 ListItem
          // 要顯示價格
          Label1.Text = ListBox1.SelectedItem.Value;
          //或 Label1.Text = ListBox1.SelectedValue;
      }
    5. 測試結果
      20231109215205
  9. List 的相關控制項,主要要放許多控制項,這些項目通常可以從資料庫取得,取得後就可以放入 List 內,這些可以不用自己用 while loop 來完成,這功能所有相關 List 控制項都有一很重要功能,要把資料丟到 List 控制項,可改寫下列:

     :
    //取出 n 筆資料
    while (sqldr.Read())
    {
      //準備 ListItem
      ListItem aaa = new ListItem();
      aaa.Text = sqldr.GetString(0); //欄位 PName
      aaa.Value = sqldr.GetInt32(1).ToString(); //欄位 Price
                                                  //放到 ListBox
      ListBox1.Items.Add(aaa);
    }

    變成為:

    //資料來源來自 SqlReader
    ListBox1.DataSource = sqldr;
    //要顯示的資料欄位
    ListBox1.DataTextField = "PNAME";
    ListBox1.DataValueField = "PRICE";
    //這個就是作前面 while 的部分,把資料一筆一筆讀到 ListBox 裡面
    ListBox1.DataBind();
    //關閉資料庫連線
    sqlcon.Close();

不使用自己寫 Ado.Net 程式的方式

  1. 前言
    前面介紹的是自己寫程式,如下的方法。

    string strcon = @"Data Source=(localdb)mssqllocaldb;Initial Catalog=im;Integrated Security=True;Pooling=False";
    SqlConnection sqlcon = new SqlConnection(strcon);
    sqlcon.Open();
    SqlCommand sqlcmd = new SqlCommand();
    sqlcmd.Connection = sqlcon;
    sqlcmd.CommandText = "select PNAME, PRICE from product ";
    SqlDataReader sqldr = sqlcmd.ExecuteReader();
    ListBox1.DataSource = sqldr;
    ListBox1.DataTextField = "PNAME";
    ListBox1.DataValueField = "PRICE";
    ListBox1.DataBind();
    sqlcon.Close();
  2. 專案上加入 WebForm2.aspx,作出與 WebForm1.aspx 相同的功能。
    20231109223826

    1. UI 部分:

      • ListBox1
      • Label1.Text = ""
        20231109224137
      • 啟用 Auto PostBack
        20231109224308
    2. 不使用任何程式碼

      1. 到控制項選取 資料 > SqlDataSource 拖曳到 WebForm2 上任一位置,這個 SqlDataSource 控制項沒有介面不同於其他控制項。
        20231109224954

        這控制項主要用來連接資料庫用

      2. 按一下設定 資料來源
        20231109225143

        • 選擇資料連接: 目的主要產生連線字串

          • 當已經建立好資料庫時:
            20231109230435
          • 無資料庫時:
            新增連接
            20231109230101
            選擇MS SQL SERVER
            20231109225943
        • 將連接字串儲存到應用程式組態檔(方案中的 Web.config)
          不建議寫到一般檔案中,容易讓別人看到,可以寫到 Web.config 會加密過
          20231109231202

          勾選: 是,將這個連接儲存為 imConnectionString,存成 Web.config,部分內容是:

          <connectionStrings>
          <add name="imConnectionString" connectionString="Data Source=(localdb)mssqllocaldb;Initial Catalog=im;Integrated Security=True;Pooling=False" providerName="System.Data.SqlClient" />
          </connectionStrings>

          用法是:
          WebForm1.aspx 中程式碼

          //引入
          using System.Web.Configuration;
          
          protected void Page_Load(object sender, EventArgs e)
          {  //還沒 PostBack
            if (!this.IsPostBack)
            {
              //建立連線字串
              //@ 避免遇到特殊字元,例如 
              //string strcon = @"Data Source=(localdb)mssqllocaldb;Initial Catalog=im;Integrated Security=True;Pooling=False";
              //回傳物件 WebConfigurationManager.ConnectionStrings["imConnection"] 中的 ConnectionString
              string strcon = WebConfigurationManager.ConnectionStrings["imConnectionString"].ConnectionString;
            }
          }

          可以把各式各樣連接字串寫(新增)到 <connectionStrings>裡面</connectionStrings>

        • 設定 Select 陳述式: 準備 SqlCommand 物件
          20231109231541

        • 測試查詢
          20231109231713
          完成後,就會產生 SqlDataReader 物件
      3. 如何使用
        點擊 ListBox 控制項上的 選擇資料來源
        20231109232248
        20231109232513

      4. 雙擊控制項 ListBox 來建立事件 ListBox1_SelectedIndexChang 方法(這事件被觸發時機在於項目改變時)

        protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
          //Label1.Text = ListBox1.SelectedItem; //找到選擇到的 ListItem
          // 要顯示價格
          Label1.Text = ListBox1.SelectedItem.Value;
          //或 Label1.Text = ListBox1.SelectedValue;
        }
      5. 測試結果
        20231109233116
最後修改日期: 2023 年 11 月 22 日

作者

留言

撰寫回覆或留言

發佈留言必須填寫的電子郵件地址不會公開。