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如有錯誤請指正,要是有其他問題請自行搜尋。

2013年6月22日 星期六

ASP.NET 使用JQuery全部取消GridView中的CheckBox

如題,有些人有寫過ASP.NET的應該都會知道,也應該會想說我只要寫一個For迴圈再去抓GridView中的CheckBox就可以了,但當你剛開始接觸JQuery(初學者)時,你可能會想說我何不透過JQuery去抓GirdView中的CheckBox呢?
我是這麼想的...直接抓全部的 input再取得類型(type)是CheckBox把它取消就可以了,這樣的好處是我不用再寫For迴圈去一個一個抓CheckBox控制項,也能輕易的抓到全部的CheckBox囉

如何實做,請看程式碼,並請實際操作...程式碼如下:

Default.aspx:
<%@ 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">
<script src="jquery-2.0.1.min.js"></script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="全部取消" />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            DataSourceID="SqlDataSource1">
            <Columns>
                <asp:TemplateField HeaderText="CheckBox">
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" />
                    </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>
   
    </div>
    </form>
</body>
</html>

Default2.aspx.vb:
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("function CB_CFalse(){")
        str_js.Append("$('input[type=checkbox]:checked').each(function () {")
        str_js.Append("$(this).attr('checked', false);")
        str_js.Append("})")
        str_js.Append("}")
        Button1.Attributes("onclick") = "CB_CFalse();"
        '假如未啟用asp.net ajax功能
        If ScriptManager.GetCurrent(Page) Is Nothing Then
            '有些情況下會需要以動態的方式加入用戶端指令碼。
            '若要動態加入指令碼,請使用 RegisterClientScriptBlock 方法、RegisterClientScriptInclude 方法、RegisterStartupScript 方法或 RegisterOnSubmitStatement 方法,視您要加入指令碼的時間和方式而定。
            'RegisterStartupScript方法會在最後面插入javascript程式碼
            Page.ClientScript.RegisterStartupScript(Me.GetType(), "wjs2", str_js.ToString, True)
        Else
            '否則有啟用asp.net ajax功能
            ScriptManager.RegisterStartupScript(Me, Me.GetType(), "wjs2", str_js.ToString, True)
        End If
    End Sub
End Class

說明:
1.<script src="jquery-2.0.1.min.js"></script>特別注意紅色標起來的這一行,您必須去JQuery的官方網站下載檔案,這個檔案有分版本,請自行下載。
2.$('input[type=checkbox]:checked').each  $為JQuery的簡易寫法,括號內的input就是抓html的input,type=checkbox就是抓input屬於checkbox的類型,運用each去抓每一個chekcbox
3.$(this).attr('checked', false);  this就是目前的checkbox,去設定checked=false

以上如有說明錯誤請指點,感謝...



ASP.NET DropDownList下拉式選單運用JavaScript變更Label值

如題...

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

<!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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    請選擇身份:
       <asp:DropDownList ID="DropDownList1" runat="server">
                    <asp:ListItem Value="0">請選擇身份</asp:ListItem>
                    <asp:ListItem Value="1">學生</asp:ListItem>
                    <asp:ListItem Value="2">管理者</asp:ListItem>
       </asp:DropDownList><br />
        <asp:Label ID="Label1" runat="server" Text="您的身分是..."></asp:Label>
        <asp:Label ID="Label2" runat="server" ></asp:Label>
    </div>
    </form>
</body>
</html>


Default.aspx.vb:
Imports System.Text
Partial Class _Default
    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("function TC(){")
        'ClientID是為了取得經過編譯後的DropDownList1控制項ID
        str_js.Append("var ddl = document.getElementById('" & DropDownList1.ClientID & "');")
        str_js.Append("var lab = document.getElementById('" & Label2.ClientID & "');")
        str_js.Append("switch(ddl.selectedIndex){")
        str_js.Append("case 1:")
        str_js.Append("lab.innerHTML='學生';")
        str_js.Append("break;")
        str_js.Append("case 2:")
        str_js.Append("lab.innerHTML='管理者';")
        str_js.Append("break;")
        str_js.Append("default:")
        str_js.Append("lab.innerHTML='';")
        str_js.Append("}}")
        DropDownList1.Attributes("onchange") = "TC();"
        '假如未啟用asp.net ajax功能
        If ScriptManager.GetCurrent(Page) Is Nothing Then
            '有些情況下會需要以動態的方式加入用戶端指令碼。
            '若要動態加入指令碼,請使用 RegisterClientScriptBlock 方法、RegisterClientScriptInclude 方法、RegisterStartupScript 方法或 RegisterOnSubmitStatement 方法,視您要加入指令碼的時間和方式而定。
            'RegisterStartupScript方法會在最後面插入javascript程式碼
            Page.ClientScript.RegisterStartupScript(Me.GetType(), "wjs2", str_js.ToString, True)
        Else
            '否則有啟用asp.net ajax功能
            ScriptManager.RegisterStartupScript(Me, Me.GetType(), "wjs2", str_js.ToString, True)
        End If
    End Sub
End Class

執行結果如下:







請自行操作體驗...

2013年5月4日 星期六

PHP 取得mysql資料庫中的資料



前置作業:
1.新增 db_mysql.ini.php 檔案
   新增 test_db.php 檔案
2.需要有mysql資料庫,並新增一個資料表,如下:




P.S上圖為測試資料,如有冒犯請告知...

程式碼:(解釋都在註解裡)
 db_mysql.ini.php:

<?php
  /**
  Step 1.mysql_connect(伺服器位置,帳號,密碼) 連線資料庫伺服器
  因資料庫在自己的電腦裡而mysql資料庫使用的port是3306,所以伺服器位置值接填入localhost:3306
  */
  if (! mysql_connect('localhost:3306','root','root')){
    //die中斷程式執行
    die('無法連線資料庫伺服器');
  }
  //Step 2.設定連線編碼為UTF8,如果您的資料庫字元集不是UTF8請自行更改
  mysql_query('SET NAMES utf8');
  //Step 3.選擇資料庫
  if (!@mysql_select_db('itn')){
    die('無法使用資料庫');
  }
  echo 'DB inc End...<br />開始準備輸出資料....<br />';
?>

test_db.php:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>取得mysql資料庫中的資料</title>
</head>
<body>
<?php
  //Step 1.引用db_mysql.inc.php檔,當引用後會去執行db_mysql.inc.php檔中所有程式碼
  include('db_mysql.inc.php');
  //執行sql指令,如查詢資料表
  $result=mysql_query('select * from users'); //執行sql指令;
  $row_total=mysql_num_rows($result);//取得資料表資料列數
  $fields=mysql_num_fields($result);//取得資料表欄位數

  //取資料表欄位名稱
  for ($x=0;$x<($fields);$x++){
    $meta=mysql_fetch_field($result);//取得欄位資訊,使用mysql_fetch_field函數目的要取得資料表欄位名稱
    $fields_name[$x]=$meta->name; //將欄位名稱儲存到$fields_name陣列
  }
  echo "<br/>筆數=$row_total;欄位數=$fields<br />";

  //先將資料存入二維資料表
  for ($y=0;$y<($row_total);$y++){
    $row=mysql_fetch_array($result);
    $db_data[$y]=$row;
  }

  //輸出資料
  echo '<table border="1">';
  for ($y=-1;$y<($row_total);$y++){
    echo '<tr>';
    for ($x=0;$x<($fields);$x++){
 //假如y等於-1就先輸出資料表欄位名稱
 if ($y==-1){
   echo '<td align="center">'.$fields_name[$x].'</td>';
 }else{
   echo '<td align="center">'.$db_data[$y][$x].'</td>';
 }
}
echo '</tr>';
  }
  echo '</table>';
?>
</body>
</html>

輸出結果:



2013年2月28日 星期四

Android點選ListView中的Item並呈現選取狀態

執行結果:
















參考資料:
ListView之一:Adapter介紹與使用 (請先參考此篇並進行實作)
[Android]讓ListView item被選擇時可以變換背景(在此篇有提到在觸碰模式下(Touch Mode)下是沒有selection state)

程式碼:
...........省略,請先參考參考資料中的資料...........
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener(){
        View view2; //保存點選的View
        int select_item=-1; //一開始未選擇任何一個item所以為-1
        public void onItemClick(AdapterView<?> parent, View view,int position, long id){
                                         
                //======================
                //點選某個item並呈現被選取的狀態
                if ((select_item == -1) || (select_item==position)){
                        view.setBackgroundColor(Color.YELLOW); //為View加上選取效果
                }else{
                        view2.setBackgroundDrawable(null); //將上一次點選的View保存在view2
                        view.setBackgroundColor(Color.YELLOW); //為View加上選取效果
                }
                view2=view; //保存點選的View
                select_item=position;//保存目前的View位置
                //======================
        }
                       
}
);
...........省略,請先參考參考資料中的資料...........


2013年2月1日 星期五

Java 實作Vector動態陣列(插入、移除)

  本篇用意是想在某些情況下,隨時將資料暫時儲存在陣列中,方便以後做處理用,這時不能用固定的陣列來儲存資料,因為資料隨時可能會儲存到陣列中,這時必須使用動態陣列來儲存資料。
PS.有興趣者自行將程式碼複製下來實際run過一次

前置作業:
新建 test_vector.java 檔

程式碼如下:
test_vector.java
import java.util.*;
import java.io.*;
public class test_vector {
public static Vector Arr_v=new Vector();
    public test_vector() {
    }
    public static void main(String[] args){
    try {
    System.out.println("實作Vector動態陣列(插入、移除)...");
    BufferedReader keyin;
   keyin=new BufferedReader(new InputStreamReader(System.in));
   boolean BStop=true;
   System.out.println("指令:close(關閉結束);length(印出陣列長度);out data(輸出陣列資料);remove(移除);\nPS.指令輸入英文即可");
 
   while(BStop){
    System.out.print("請輸入資料或輸入指令:");
       String str_data=keyin.readLine();
if (str_data.equals("length")){
System.out.println("Arr_v長度:"+Arr_v.size());
}else if (str_data.equals("close")){
BStop=false;
System.out.println("End...");
}else if (str_data.equals("out data")){
System.out.println("================");
System.out.println("輸出資料...");
for (int y=0;y<Arr_v.size();y++){
//((Vector)Arr_v.elementAt(y)).elementAt(1).toString() //印出(輸出)二維陣列的資料
//印出(輸出)一維陣列的資料
System.out.println("Arr_v["+y+"]="+Arr_v.elementAt(y).toString());
}
System.out.println("================");
}else if (str_data.equals("remove")){
synchronized(Arr_v){
try{
System.out.print("請輸入要移除的陣列(從0開始):");
//Integer.parseInt 將輸入的值轉換為int(整數),並丟入x_index變數中
int x_index= Integer.parseInt(keyin.readLine());
//remove 移除所指定的陣列,並將移除的值強制轉換為String(字串),
String str_temp=(String)Arr_v.remove(x_index);
System.out.println("移除Arr_v["+x_index+"]="+str_temp);
}catch(Exception e) {
System.out.println(e.toString());
}
}
}else{
synchronized(Arr_v){
Arr_v.add(Arr_v.size(),str_data); //將資料放入到Vector中
}
}
   }
    }catch(IOException e){
    System.out.println("Error IOException:"+e.toString());
    }catch(Exception e) {
    System.out.println("Error Exception:"+e.toString());
    }
    }
}

輸出結果如下: