[習題]給初學者的範例,多重欄位搜尋引擎 for GridView #2(完全手寫、後置程式碼!),兼論 SqlDataSource與SelectParameter用法

摘要:給初學者的範例,多重欄位搜尋引擎 for GridView #2

自己動手寫程式
透過 SqlDataSource來作,以「組合SQL指令」的方式,搜尋多個欄位。



原文出處:  http://www.taconet.com.tw/mis2000_aspnet/     這是我以前的網站

 

請先看過這篇文章的說明--

[習題]給初學者的範例,多重欄位搜尋引擎 for GridView #1 (http://www.dotblogs.com.tw/mis2000lab/archive/2008/04/25/3503.aspx)

 

 

為了解決這個問題,所以程式改寫如下:

 

HTML畫面

================================================================================

        Title:        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
        Summary:        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
        Article:        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>

        <asp:Button ID="Button1" runat="server" Text="Search~" /><br />

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
            DataKeyNames="id" AllowPaging="True" PageSize="3"
            DataSourceID="SqlDataSource1">

            <Columns>
                <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True" SortExpression="id" />
                <asp:BoundField DataField="test_time" HeaderText="test_time" SortExpression="test_time" DataFormatString="{0:yyyy/MM/dd}" HtmlEncode="False" />
                <asp:BoundField DataField="title" HeaderText="title" SortExpression="title" >
                    <ItemStyle Font-Bold="True" Font-Size="Medium" ForeColor="#004000" />
                </asp:BoundField>
                <asp:BoundField DataField="summary" HeaderText="summary" SortExpression="summary" />
                <asp:BoundField DataField="article" HeaderText="article" SortExpression="article" >
                    <ItemStyle Font-Size="X-Small" ForeColor="Purple" />
                </asp:BoundField>
                <asp:BoundField DataField="author" HeaderText="author" SortExpression="author" />
            </Columns>

            <EmptyDataTemplate>
                <strong><span style="font-size: 16pt; color: #ff0000">Sorry!!....NOTHING!!</span></strong>
            </EmptyDataTemplate>
        </asp:GridView>


        <asp:SqlDataSource ID="SqlDataSource1" runat="server"  ConnectionString="<%$ ConnectionStrings:testConnectionString %>">

            註解:  SqlDataSource裡面是空的!!
        </asp:SqlDataSource>

 

以下是後置程式碼,本文提供VB / C#兩種版本給大家參考:

================================================================================

Code-Behind (for VB)

================================================================================

因為上方的HTML碼裡面,已經有一個「空的」 SqlDataSource,

裡面也有資料庫連線字串了,所以底下的 DBInit()只需要拼湊、「組合」出適當的 SQL指令即可。

01     Sub myDBInit()
02         '== SqlDataSource精靈 自動產生的SQL指令,可以當作參考 ==
03         'SqlDataSource1.SelectCommand = "SELECT * FROM [test] WHERE (([title] LIKE '%' + @title + '%') AND ([summary] LIKE '%' + @summary + '%') AND ([article] LIKE '%' + @article + '%'))"
04
05         SqlDataSource1.SelectParameters.Clear()
06
07         '==以下是自己改寫的「多重欄位 搜尋引擎」,SQL指令的文字組合 ==
08         Dim mySQLstr As String = " 1=1 "
09
10         If TextBox1.Text <> "" Then
11             mySQLstr = mySQLstr + " AND ([title] LIKE '%' + @title + '%')"
12             '== 重點在此:參數必須寫在IF判別式這裡,不能一起寫在後面。==
13             '== 否則,寫在下面那區,所有出現的參數,不能留白! ==
14             SqlDataSource1.SelectParameters.Add("title", TextBox1.Text)
15         End If
16         If TextBox2.Text <> "" Then
17             mySQLstr = mySQLstr + " AND ([summary] LIKE '%' + @summary + '%')"
18             SqlDataSource1.SelectParameters.Add("summary", TextBox2.Text)
19         End If
20         If TextBox3.Text <> "" Then
21             mySQLstr = mySQLstr + " AND ([article] LIKE '%' + @article + '%')"
22             SqlDataSource1.SelectParameters.Add("article", TextBox3.Text)
23         End If
24
25         '============================================
26         '== 連結資料庫的連接字串 ConnectionString  ==
27         'SqlDataSource1.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings("testConnectionString").ConnectionString
28         '== 撰寫SQL指令 ==
29         SqlDataSource1.SelectCommand = "SELECT * FROM [test] WHERE " + mySQLstr
30
31         Response.Write("<hr>您要搜尋哪些欄位?SQL指令為  " & SqlDataSource1.SelectCommand & "<hr>")
32         '== 重點在此:參數必須寫在上面的「每一個IF判別式」裡面,不能一起寫在這邊。==
33         '== 否則,這裡有出現的參數,就必須有「值」,不能留白! ==
34         'SqlDataSource1.SelectParameters.Add("title", TextBox1.Text)
35         'SqlDataSource1.SelectParameters.Add("summary", TextBox2.Text)
36         'SqlDataSource1.SelectParameters.Add("article", TextBox3.Text)
37
38         '== 執行SQL指令 .select() ==
39         'Dim dv As Data.DataView = SqlDataSource1.Select(New DataSourceSelectArguments)
40
41         'GridView1.DataSource = dv
42         'GridView1.DataBind()
43         '============================================
44     End Sub

45
46     Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
47         If GridView1.PageIndex <> 0 Then
48             '==如果不加上這行IF判別式,當我們看第四頁時,
49             '==又輸入新的條件,重新作搜尋。「新的」搜尋結果將會直接看見第四頁!===
50             GridView1.PageIndex = 0
51         End If
52         myDBInit()
53     End Sub

54
55     Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView1.PageIndexChanging
56         GridView1.PageIndex = e.NewPageIndex
57
58         Response.Write("目前位於第" & CInt(e.NewPageIndex.ToString()) + 1 & "頁<br>")
59         '== 必須把 GridView1 的 [EnableSortingAndPagingCallBack]屬性關閉(=False),才會執行到這一行! ==
60     End Sub

61
62     Protected Sub GridView1_PageIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.PageIndexChanged
63         myDBInit()
64     End Sub

 

================================================================================

Code-Behind (for C#)

================================================================================

因為上方的HTML碼裡面,已經有一個「空的」 SqlDataSource,

裡面也有資料庫連線字串了,所以底下的 DBInit()只需要拼湊、「組合」出適當的 SQL指令即可。

01     protected void DBInit()
02     {
03         //== SqlDataSource精靈   自動產生的SQL指令,可以當作參考 ==
04         SqlDataSource1.SelectParameters.Clear();
05
06         //==以下是自己改寫的「多重欄位 搜尋引擎」,SQL指令的文字組合 ==
07         string mySQLstr = " 1=1 ";   //請注意, 1=1後面多一個空白!
08
09         if (TextBox1.Text != "")
10         {
11             mySQLstr = mySQLstr + " AND ([title] LIKE '%' + @title + '%')";
12             //== 重點在此:參數必須寫在IF判別式這裡,不能一起寫在後面。==
13             SqlDataSource1.SelectParameters.Add("title", TextBox1.Text);
14         }

15             
16         if (TextBox2.Text != "")
17         {
18             mySQLstr = mySQLstr + " AND ([summary] LIKE '%' + @summary + '%')";
19             SqlDataSource1.SelectParameters.Add("summary", TextBox2.Text);
20         }

21
22         if (TextBox3.Text != "")
23         {
24             mySQLstr = mySQLstr + " AND ([article] LIKE '%' + @article + '%')";
25             SqlDataSource1.SelectParameters.Add("article", TextBox3.Text);
26         }

27
28         //============================================
29         //== SqlDataSource1 資料庫的連接字串 ConnectionString,
30         //== 已事先寫在「HTML畫面的設定」裡面 ==
31         //============================================
32
33         //== 最後,合併成完整的SQL指令(搜尋引擎~專用) ==
34         SqlDataSource1.SelectCommand = "SELECT * FROM [test] WHERE " + mySQLstr;
35
36         //==================================================
37         //== 執行SQL指令 與 GridView1.DataBind()的部份,均已經事先寫好
38         //==在「HTML畫面的設定」上,也就是下面這一行,就通通搞定了。ASP.NET 真強!
39         //==<asp:GridView ID="GridView1" DataSourceID="SqlDataSource1">
40         //==================================================
41
42         Response.Write("<hr>您要搜尋哪些欄位?SQL指令為  " + SqlDataSource1.SelectCommand + "<hr>");
43         //== 重點在此:參數必須寫在上面的「每一個IF判別式」裡面,不能一起寫在這邊。==
44         //== 否則,這裡有出現的參數,就必須有「值」,不能留白! ==
45         //SqlDataSource1.SelectParameters.Add("title", TextBox1.Text);
46         //SqlDataSource1.SelectParameters.Add("summary", TextBox2.Text);
47         //SqlDataSource1.SelectParameters.Add("article", TextBox3.Text);
48
49         //== 執行SQL指令 .select() ==
50         //DataView dv = SqlDataSource1.Select(new DataSourceSelectArguments);
51
52         //GridView1.DataSource = dv;
53         //GridView1.DataBind();
54         //============================================
55     }

56
57     protected void Button1_Click(object sender, EventArgs e)
58     {
59         if (Convert.ToInt32(GridView1.PageIndex) != 0)
60         {
61            //==如果不加上這行IF判別式,假設當我們看第四頁時,
62            //==又輸入新的條件,重新作搜尋。「新的」搜尋結果將會直接看見 "第四頁"!這個問題發生在這裡,請看!===
63            GridView1.PageIndex = 0;
64         }

65
66         DBInit();
67     }

68
69     protected void  GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
70     {
71             GridView1.PageIndex = e.NewPageIndex;
72
73             Response.Write("目前位於第" + (Convert.ToInt32(e.NewPageIndex) + 1) + "頁<br>");
74             //== 把 GridView1 的 [EnableSortingAndPagingCallBack]屬性關閉(=False),才會執行到這一行! ==
75     }

76
77     protected void  GridView1_PageIndexChanged(object sender, EventArgs e)
78     {
79         DBInit();
80     }

 

原文出處:我以前的網站  http://www.taconet.com.tw/mis2000_aspnet/

 

2010/6/7補充

關於本文,我已經重新整理一篇新的文章了,請看:

[文章下載]網站內的搜尋引擎,單一欄位與多重欄位的搜尋(自己手寫SqlDataSource與SelectParameter參數)

 

 

 

 

 

 2010/3/5補充 --

黑暗執行緒的文章 , http://blog.darkthread.net/blogs/darkthreadtw/archive/2010/03/02/or-operator-in-sql.aspx

 

 

 

 

上面的程式碼,可能遭受資料隱碼(SQL Injection)的攻擊,請各位小心。

關於SQL Injection的介紹與解法,可以參考黃忠成老師的大作

LINQ - 對付 SQL Injection 的 '免費補洞策略'LINQ - 對付 SQL Injection 的 "免費補洞策略"
一連串的 Mass SQL Injection 攻擊,讓我們回憶起數年前的 SQL Injection 攻擊,多年後的今天,我們仍深陷於同樣的危機中,本文詳述 SQL Injection 的歷史、肇因、解決及偵測方法,更為讀者們引介全新、更加安全的防堵 SQL Injection 策略。

 

 

 

2010/5/19補充:

本範例除了介紹 SqlDataSource的後置程式碼該怎麼撰寫之外

也介紹到 SelectParameter的寫法。

 

  • SqlDataSource的 UpdateCommand與  UpdateParameter 、  DeleteCommand與DeleteParameter  的用法,請參考這個範例:

ADO.NET #3 (GridView + SqlDataSource)完全手寫、後置程式碼 ...

 

感謝網友Alan留言並分享了這個好範例:
 

 

 

 

我將思想傳授他人, 他人之所得,亦無損於我之所有;

猶如一人以我的燭火點燭,光亮與他同在,我卻不因此身處黑暗。----Thomas Jefferson

線上課程教學,遠距教學 (Web Form 約 51hr)  https://dotblogs.com.tw/mis2000lab/2016/02/01/aspnet_online_learning_distance_education_VS2015

線上課程教學,遠距教學 (ASP.NET MVC 約 135hr)  https://dotblogs.com.tw/mis2000lab/2018/08/14/ASPnet_MVC_Online_Learning_MIS2000Lab

 

寫信給我,不要私訊 --  mis2000lab (at) yahoo.com.tw  或  school (at) mis2000lab.net

 (1) 第一天 ASP.NET MVC5 完整影片(5.5小時 / .NET 4.x版)免費試聽。影片 https://youtu.be/9spaHik87-A 

 (2) 第一天 ASP.NET Core MVC 完整影片(3小時 / .NET Core 6.0~8.0)免費試聽。影片 https://youtu.be/TSmwpT-Bx4I 

[學員感言] mis2000lab課程評價 - ASP.NET MVC , WebForm  。 https://mis2000lab.medium.com/%E5%AD%B8%E5%93%A1%E6%84%9F%E8%A8%80-mis2000lab%E8%AA%B2%E7%A8%8B%E8%A9%95%E5%83%B9-asp-net-mvc-webform-77903ce9680b  


ASP.NET遠距教學、線上課程(Web Form + MVC)。 第一天課程, "完整" 試聽。 

.........   facebook社團   https://www.facebook.com/mis2000lab   ......................

.........  YouTube (ASP.NET) 線上教學影片  https://www.youtube.com/channel/UC6IPPf6tvsNG8zX3u1LddvA/

 

Blog文章 "附的範例" 無法下載,請看 https://dotblogs.com.tw/mis2000lab/2016/03/14/2008_2015_mis2000lab_sample_download

請看我們的「售後服務」範圍(嚴格認定)。

...................................................................................................................................................... 

ASP.NET MVC  => .NET Core MVC 線上教學  ...... 第一天課程 完整內容 "免費"讓您評估 / 試聽

[遠距教學、教學影片] ASP.NET (Web Form) 課程 上線了!MIS2000Lab.主講   事先錄好的影片,並非上課側錄!   觀看時,有如「一對一」面對面講課