2013年7月23日 星期二

ASP.NET、HTML 限制TextBox輸入的資料

重點紀錄與整理:實作TextBox限制使用者只能輸入英文及數字符號、限制使用者不能剪下複製貼上、運用css限制TextBox使輸入法失效。

Default5.aspx
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default5.aspx.vb" Inherits="Default5" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="jquery-2.0.1.min.js"></script>
<script>
$(function () {
$('#TextBox1').bind('cut copy paste', function (e) {
e.preventDefault(); //取消動作
alert('禁止剪下複製貼上');
});
$('#Html_TextBox').bind('cut copy paste', function(e) {
    e.preventDefault(); //取消動作
    alert('禁止剪下複製貼上');
});
});
</script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        實作TextBox限制只能輸入英文及數字符號、限制使用者不能剪下複製貼上、運用css限制TextBox使輸入法失效<br />
        以下為ASP.NET TextBox控制項<br />
        <asp:TextBox ID="TextBox1" runat="server" Height="110px" style="ime-mode:Disabled;"
            TextMode="MultiLine" Width="276px"></asp:TextBox><br />
        以下為HTML TextBox多行輸入控制項<br />
        <textarea rows="10" style="width: 271px;ime-mode:Disabled;" id="Html_TextBox" onkeyup="value=value.replace(/^a-zA-Z0-9/)"></textarea>
        <asp:Button ID="Button2" runat="server" Text="Button" />
    </div>
    </form>
</body>
</html>

Default5.aspx.vb
Partial Class Default5
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        '為ASP.NET TextBox控制項加入客戶端onkeyup事件用運javascript的replace函式搭配正規表示式來限制使用者輸入的資料
        TextBox1.Attributes("onkeyup") = "value=value.replace(/^a-zA-Z0-9/)"
    End Sub

End Class

說明
1. style="ime-mode:Disabled;" 利用CSS來限制使用者僅能輸入英文和數字及符號;其實在程式碼當中也有寫到JavaScript語法的replace函式來限制使用者僅能輸入英文和數字及符號,在這裡就看您想用哪一種方法來限制使用者所輸入的資料

資料來源:
[jQuery] TextBox中禁止剪下複製貼上
輕鬆解決網頁只能輸入英數字的問題

2013年7月6日 星期六

ASP.NET 利用JQuery設定控制項選取項目、啟用、隱藏

有時候我們可能在寫程式時會寫到SQL查詢功能,又或者會寫到表單的填寫,在網頁上都會有一些像是DropDownList(下拉式選單)控制項,當我選了某一個項目時就會啟用另外一個控制項,通常為了達到這樣的效果,都會去設定DropDownList控制項的AutoPostBack屬性,這時當我選取下拉式選單的項目時,就會去啟用另外一個控制項,就會照成頁面的刷新,如果不想要讓頁面刷新,那你就必須再使用ajax控制項的UpdatePanel,來達成非同步的更新。如果不想要這麼作,那還有另外一個方法就是在網頁上寫JavaScript、JQuery等語法來完成。

功能敘述:當我選取DDL1下拉式選單時,就會啟用另外一個DDL2下拉式選單,當我又選取DDL2的學生姓名選項時,又會去將隱藏起來的TextBox顯示出來,讓使用者進去條件的查詢。

前置作業:
1.先新增一個網頁名為:Default2.aspx

HTML:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default2.aspx.vb" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="jquery-2.0.1.min.js"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="DDL1" runat="server">
            <asp:ListItem Value="-1">請選擇查詢方式</asp:ListItem>
            <asp:ListItem Value="0">未測驗</asp:ListItem>
            <asp:ListItem Value="1">不合格者</asp:ListItem>
            <asp:ListItem Value="2">合格者</asp:ListItem>
        </asp:DropDownList>&nbsp;
        <asp:DropDownList ID="DDL2" runat="server" Enabled="false">
            <asp:ListItem Value="-1">全部</asp:ListItem>
            <asp:ListItem Value="0">學生姓名</asp:ListItem>
        </asp:DropDownList>&nbsp;
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="查詢" Enabled="false"/>
    </div>
    </form>
</body>
</html>

後置程式碼:
Imports System.Text
Partial Class Default2
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim str_js As New StringBuilder

        str_js.Append("$(document).ready(function(){")
        str_js.Append("$('#" & TextBox1.ClientID & "').hide();")
        str_js.Append("$('#" & DDL1.ClientID & "').change(")
        str_js.Append("function(){")
        str_js.Append("var str_text=$('#" & DDL1.ClientID & "').find(':selected').text();") '取得被選擇項目的文字
        str_js.Append("var str_value=$('#" & DDL1.ClientID & "').find(':selected').val();") '取得被選擇項目的值
        'true停用,啟用它就設成false;再asp.net控制項則是相反enabled=true為啟用,enabled=false則不啟用
        str_js.Append("if(parseInt(str_value)==-1){$('#" & DDL2.ClientID & "').attr('disabled',true);" & _
                      "$('#" & DDL2.ClientID & "').find('option:eq(0)').attr('selected', true);" & _
                      "$('#" & Button1.ClientID & "').attr('disabled',true);" & _
                      "$('#" & TextBox1.ClientID & "').hide();" & _
                      "}else{$('#" & DDL2.ClientID & "').attr('disabled',false);" & _
                      "$('#" & Button1.ClientID & "').attr('disabled',false);}")
        str_js.Append("});")
        str_js.Append("$('#" & DDL2.ClientID & "').change(")
        str_js.Append("function(){")
        str_js.Append("var str_value2=$('#" & DDL2.ClientID & "').find(':selected').val();")
        str_js.Append("if(parseInt(str_value2)==-1){$('#" & TextBox1.ClientID & "').hide();" & _
                     "}else{$('#" & TextBox1.ClientID & "').show();}")
        str_js.Append("});")
        str_js.Append("});")

        If ScriptManager.GetCurrent(Page) Is Nothing Then
            '未啟用asp.net ajax功能
            '有些情況下會需要以動態的方式加入用戶端指令碼。 若要動態加入指令碼,請使用 RegisterClientScriptBlock 方法、RegisterClientScriptInclude 方法、RegisterStartupScript 方法或 RegisterOnSubmitStatement 方法,視您要加入指令碼的時間和方式而定。
            Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Default2", str_js.ToString, True)
        Else
            '啟用asp.net ajax功能
            ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "Default2", str_js.ToString, True)
        End If
    End Sub
End Class

說明:
1. <script src="jquery-2.0.1.min.js"></script> 引用JQuery檔案,要引用才能撰寫JQuery
2.有人會發現,我將JQuery寫在後置程式碼裡,透過RegisterClientScriptBlock方法將撰寫好的JQuery直接插入到html裡(你可以按滑鼠右鍵→檢視原始檔,就會發現JQuery程式碼已經插入到html當中),就可以執行JQuery程式碼
其餘改日再補充...

2013年7月3日 星期三

ASP.NET 點選GridView中的Button,並取得該列(Row)的欄位值

如題,就是當我點選GridView中的Button時,我同時也要取得被我點選該列的欄位值。這樣的小技巧常會被用來更新資料或者當我按下按鈕時,切換畫面後並將GridView中的資料順便傳給下一個畫面...等技巧就看您怎麼去運用。這個問題去搜尋都找得到,自此我只是將經驗記錄下來。

前置作業:
1.準備好資料庫(待會要讓GridView顯示資料用)
以上準備好後,就跟在步驟做一遍吧~

步驟如下:
Step 1.紅色的部份請在GridView中加上
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            DataSourceID="SqlDataSource1">
            <Columns>
                <asp:TemplateField HeaderText="Button">
                    <ItemTemplate>
                        <asp:Button ID="Button1" runat="server" Text="Show 1" 
                           onclick="Button1_Click" />
                        <asp:Button ID="Button2" runat="server" Text="Show 2"  
                           CommandName="ShowData" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="test_id" HeaderText="test_id" InsertVisible="False"
                    ReadOnly="True" SortExpression="test_id" />
                <asp:BoundField DataField="test_name" HeaderText="test_name"
                    SortExpression="test_name" />
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
            SelectCommand="SELECT * FROM [test_T]"></asp:SqlDataSource>

Step 2.因我將Button2的CommandName屬性設定了值,而這個值等同於GridView中按鈕的命令,當我按下時,則會去處發GridView中的RowCommand事件;而另外一個Button1則是普通的Click事件;我將針對著兩個Button做個別的程式撰寫,但效果都是一樣的。
..................
    Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
        If e.CommandName = "ShowData" Then
            Dim Bu1 As Button = CType(e.CommandSource, Button) '先取得命令的來源並轉換成按鈕
            Dim GV_Row As GridViewRow = CType(Bu1.NamingContainer, GridViewRow) '將Button轉換成GridViewRow就是您所點選的某一列

            MsgBox(CType(GV_Row.FindControl("Button2"), Button).ClientID & ";" & GV_Row.Cells(1).Text & ";" & GV_Row.Cells(2).Text)
        End If
    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim Bu2 As Button = CType(sender, Button) '直接將Button1_Click事件中的sender參數轉換成按鈕
        Dim GV_Row As GridViewRow = CType(Bu2.NamingContainer, GridViewRow) '將Button轉換成GridViewRow就是您所點選的某一列

        MsgBox(CType(GV_Row.FindControl("Button1"), Button).ClientID & ";" & GV_Row.Cells(1).Text & ";" & GV_Row.Cells(2).Text)
    End Sub
..................

執行結果:












說明:
1.MsgBox是在VB.NET裡才有的東西,如果想在網頁中顯示訊息框,那您得使用JavaScript等其他方法來顯示。
2.CType(GV_Row.FindControl("Button1"), Button).ClientID 這段的意思是我將抓到的Button1轉換成Button,轉換完後取得他的Client ID,有些控制項經過網頁編譯後他就不是程式碼中原本的ID。
3.那既然可以寫Button_Click事件裡,為什麼還要寫在GridView的RowCommand事件呢?
寫在RowCommand事件的好處就是,當你有為GridView設定CommandArgument屬性時,我就可以透過Dim str_pk As String = CStr(e.CommandArgument)這行程式碼很容易的取得資料表的主鍵

P.S如有錯誤請指正,要是有其他問題請自行搜尋。