TOP

[Javascript] RadioButton 切換選項時,同時變更顯示圖片

RadioButton 切換選項時,同時變更額外想要變更的圖片

VB.Net
<script language="javascript">
function changeRadioImg(radioBox) {
        var RB1 = document.getElementById('<%= rbList.ClientID %>');
        var radio = RB1.getElementsByTagName("input");
        var image = document.getElementById('Img');
        for (var i = 0; i < radio.length; i++)
          {
            if (radio[i].checked)
                {
                 image.src = "";
                }
            }
        }
</script>

<img id="Img" alt="Img"/>
<div class="abc" style="WIDTH: 770px;HEIGHT: 100px;overflow-x:scroll;text-align:center;vertical-align :middle;border-style:outset; border-width:1px">
<asp:RadioButtonList ID="rbList" runat="server" DataTextField="img" DataValueField="id"
        RepeatDirection="Horizontal" TextAlign="Left" DataTextFormatString="<img src='{0}/><br>">         </asp:RadioButtonList>
</div>

ClientScript.RegisterStartupScript(Me.GetType(), "changeRadioImg", "<script type='text/javascript'>changeRadioImg(document.getElementById('" + rbList.ClientID + "'));</script>")
TOP

[C#][ASP.NET]RadioButtonList 圖片選擇項目

一般RadioButtonList都是使是文字的方式來讓使用者選擇項目,這次遇到希望使用圖片來選擇項目的需求

VB.Net

<asp:RadioButtonList ID="rbList" runat="server" DataTextField="img" DataValueField="id"
         RepeatDirection="Horizontal" TextAlign="Left"
  DataTextFormatString="<img src='{0}'/><br>">                                                                                    
 </asp:RadioButtonList>

    Private Class ConfSettingItem
        Public Sub New(ByVal id As String, ByVal img As String, ByVal Value As String)
            Me.id = id
            Me.img = img
            Me.Value = Value
        End Sub
        Private _id As String
        Private _img As String
        Private _Value As String

        Public Property id() As String
            Get
                Return _id
            End Get
            Set(ByVal value As String)
                _id = value
            End Set
        End Property

        Public Property img() As String
            Get
                Return _img
            End Get
            Set(ByVal value As String)
                _img = value
            End Set
        End Property

        Public Property Value() As String
            Get
                Return _Value
            End Get
            Set(ByVal value As String)
                _Value = value
            End Set
        End Property

    End Class

     Dim infos As New List(Of ConfSettingItem)

     infos.Add(New ConfSettingItem(id, url, value))
     infos.Add(New ConfSettingItem(id, url, value))
     rbList.DataSource = infos
     rbList.DataBind()

以上方式也可以改直接使用ListItemCollection更為簡單

<asp:RadioButtonList ID="rbList" runat="server"  RepeatDirection="Horizontal" TextAlign="Left"
  DataTextFormatString="<img src='{0}'/><br>">                                                                                  
 </asp:RadioButtonList>

     Dim infos As New ListItemCollection()
     infos.Add(New ListItem(url, id))
     rbList.DataSource = infos
     rbList.DataBind()

C#

<asp:RadioButtonList ID="rbList" runat="server" DataTextField="img" DataValueField="id"
        RepeatDirection="Horizontal" TextAlign="Left"
         DataTextFormatString="<img src='{0}' />">                                                                                        </asp:RadioButtonList>

 private class ConfSettingItem
 {
    public string id { get; set; }
    public string img { get; set; }
    public string Value { get; set; }
 }

 List<ConfSettingItem> infos = new List<ConfSettingItem>
 {
  new ConfSettingItem{ id="", img="", Value=""},
  new ConfSettingItem{ id="", img="", Value=""},
 };

infos .Add(new ConfSettingItem { id = "", img = "", Value = "" });

 rbList.DataSource = infos;
 rbList.DataBind();
TOP

[Javascript] textbox 點擊時自動全選

使用者原本希望點擊button時就自動全選並且復製textbox內容,但因為瀏覽器的安全機制,只有IE可以做到,Firfox及chrome都沒有辨法做到。

所以改為點擊textbox時,就自動全選。
使用者在自已點選右鍵「復製」。

onfocus="this.select()" onMouseUp="return false"

<asp:TextBox ID="tb1" onfocus="this.select()" onMouseUp="return false" runat="server" ></asp:TextBox>
TOP

[JavaScript]Firefox onClick return false but it doesn't work

Firefox onClick return false but it doesn't work

問題:IE及Chorme使用onClick 當回傳false後就利用window.event.cancelBubble = true停止執行。

但在Firefox測試時發生,還是一樣執行接下來的事件。

因此在firefox時需變成使用    e.stopPropagation()停止執行。

if (window.event) //for IE
 {
  window.event.cancelBubble = true;
 }
 else //for Firefox
 {
    var e = arguments.callee.caller.arguments[0] || event;
    e.stopPropagation();
  }

資料來源:http://blog.darkthread.net/post-2008-06-26-stop-event-bubbling.aspx
TOP

[PHP] include其他php檔時,中文出現亂碼

利用mb_convert_encoding解決中文出現亂碼 的問題

$ABC = mb_convert_encoding($ABC, "UTF-8", "BIG5");
TOP

[PHP][轉貼]PHP內使用mysql相關語法

[轉貼]PHP內使用mysql相關語法

原文出處:http://austintodo.pixnet.net/blog/post/23821431-php---mysql-%E6%95%99%E5%AD%B8

這邊有個php mysql 教學的網站
http://www.php-mysql-tutorial.com/
用php+mysql也是行之有年了...
紀錄一下在php內怎麼使用mysql相關語法
More »
TOP

[PHP] [轉貼] PHP 分頁 函數

轉貼兩個不錯的PHP 分頁函數

(1)參考資料:http://blog.xuite.net/kinds/PHPandCSS/13159453

<?
//為了避免重復包含文件而造成錯誤,加了判斷函數是否存在的條件:
if(!function_exists(pageft)){
//定義函數pageft(),三個參數的含義為:
//$totle:資訊總數;
//$displaypg:每頁顯示資訊數,這裏設置預設是20;
//$url:分頁瀏灠中的鏈結,除了加入不同的查詢資訊"page"外的部分都與這個URL相同。
//   預設值本該設為本頁URL(即$_SERVER["REQUEST_URI"]),但設置預設值的右邊只能為常量,所以該預設值設為空字串,在函數內部再設置為本頁URL。
function pageft($totle,$displaypg=20,$url=''){
//定義幾個總體變數:
//$page:當前頁碼;
//$firstcount:(資料庫)查詢的起始項;
//$pagenav:頁面導航條代碼,函數內部並沒有將它輸出;
//$_SERVER:讀取本頁URL"$_SERVER["REQUEST_URI"]"所必須。
global $page,$firstcount,$pagenav,$_SERVER;
//為使函數外部可以訪問這裏的"$displaypg",將它也設為總體變數。注意一個變數重新定義為總體變數後,原值被覆蓋,所以這裏給它重新賦值。
$GLOBALS["displaypg"]=$displaypg;
if(!$page) $page=1;
//如果$url使用預設,即空值,則賦值為本頁URL:
if(!$url){ $url=$_SERVER["REQUEST_URI"];}
//URL分析:
$parse_url=parse_url($url);
$url_query=$parse_url["query"]; //單獨取出URL的查詢字串
if($url_query){
//因為URL中可能包含了頁碼資訊,我們要把它去掉,以便加入新的頁碼資訊。
//這裏用到了正則運算式,請參考本站的相關文章
$url_query=ereg_replace("(^|&)page=$page","",$url_query);
//將處理後的URL的查詢字串替換原來的URL的查詢字串:
$url=str_replace($parse_url["query"],$url_query,$url);

//在URL後加page查詢資訊,但待賦值:
if($url_query) $url.="&page"; else $url.="page";
}else {
$url.="?page";
}
頁碼計算:
$lastpg=ceil($totle/$displaypg); //最後頁,也是總頁數
$page=min($lastpg,$page);
$prepg=$page-1; //上一頁
$nextpg=($page==$lastpg ? 0 : $page+1); //下一頁
$firstcount=($page-1)*$displaypg;
//開始分頁導航條代碼:
$pagenav="顯示第 <B>".($totle?($firstcount+1):0)."</B>-<B>".min($firstcount+$displaypg,$totle)."</B> 條記錄,共 $totle 條記錄<BR>";
//如果只有一頁則跳出函數:
if($lastpg<=1) return false;
$pagenav.=" <a href='$url=1'>首頁</a> ";
if($prepg) $pagenav.=" <a href='$url=$prepg'>前頁</a> "; else $pagenav.=" 前頁 ";
if($nextpg) $pagenav.=" <a href='$url=$nextpg'>後頁</a> "; else $pagenav.=" 後頁 ";
$pagenav.=" <a href='$url=$lastpg'>尾頁</a> ";
//下拉跳轉列表,迴圈列出所有頁碼:
$pagenav.=" 到第 <select name='topage' size='1' onchange='window.location=\"$url=\"+this.value'>\n";
for($i=1;$i<=$lastpg;$i++){
if($i==$page) $pagenav.="<option value='$i' selected>$i</option>\n";
else $pagenav.="<option value='$i'>$i</option>\n";
}
$pagenav.="</select> 頁,共 $lastpg 頁";
}
}
?>
好,分頁函數已經寫好了,保存為"pageft.php",要分頁時就包含它並調用pageft()函數。不過它並沒有輸出任何東西,但產生幾個總體變數供使用:$firstcount、$displaypg、$pagenav。


下面舉例說明它的用法:




<?
//(前面程式略)
include("pageft.php"); //包含"pageft.php"文件
//取得總資訊數
$result=mysql_query("select * from mytable");
$total=mysql_num_rows($result);
//調用pageft(),每頁顯示10條資訊(使用預設的20時,可以省略此參數),使用本頁URL(預設,所以省略掉)。
pageft($total,10);
//現在產生的總體變數就派上用場了:
$result=mysql_query("select * from mytable limit $firstcount,$displaypg ");
while($row=mysql_fetch_array($result)){
//(列表內容略)
}
//輸出分頁導航條代碼:
echo $pagenav;
//(後面程式略)
?>

備註:
發現文章有點問題,無法正確顯示後面分頁,因為程式根本無法獲取$page變數,解決方法:
include("pageft.php"); //包含“pageft.php”文件
$page=$_GET['page'];//加上這句即可


又一個錯誤,當數據記錄為0時,php報錯,加入以下代碼:

$total=mysql_num_rows($result);
if ($total==0 )die("暫時沒有資訊!");//如果記錄為0


參考資料:http://big5.china.com/gate/big5/zehao123.blog.china.com/201103/7878436.html

(2)參考資料:http://peeress.pixnet.net/blog/post/27760247
潔西卡 寫的分頁函數。
Call sample:
#計算筆數先
$offset = $_REQUEST["offset"] == "" ? 0 ; $_REQUEST["offset"];
$mrows = $conn->Execute("select count(a_account) as T from $TABLE_NAME $WHERE_STR ");
$mrow = $mrows->FetchObject();
$numrows = $mrow->T;
$pagestr = pages($numrows, $offset, $num_of_rows_per_page,"type=$type","no9", 2);
print $pagestr; // 印出分頁
$rows = $conn->SelectLimit($sql,$num_of_rows_per_page,$offset);
while ($row = $rows->fetchRow()) {
// 略 這裡是SHOW 資料
}
print $pagestr; // 印出分頁


結束
############# 下面是函數 弄成一個INCLUDE FILE 吧 ############
function pages($total_rows, $offset, $limit_row,$url_str='', $class="page", $mod="2") {
$current_page = ($offset/$limit_row) + 1;
$total_pages = ceil($total_rows/$limit_row);
if ($mod == "1") {
$current_page = ($offset/$limit_row) + 1;
$total_pages = ceil($total_rows/$limit_row);
$str2 = "";
if ($offset != 0) $str2 .="| <a href=\"$PHP_SELF?offset=0&$url_str\" class=\"$class\">FirstPage</a> | ";
if (($offset - $limit_row) >= 0) {
$prev_offset = $offset - $limit_row;
$str2 .= " <a href=\"$PHP_SELF?offset=$prev_offset&$url_str\" class=\"$class\">Previous</a> | ";
}
$str2 .= " [ $current_page / $total_pages ] ";
$last_row = (($total_pages-1) * $limit_row);
if (($offset + $limit_row) < $total_rows) {
$next_offset = $offset + $limit_row;
$str2 .= "<a href=\"$PHP_SELF?offset=$next_offset&$url_str\" class=\"$class\">NEXT</a> | ";
$str2 .= "<a href=\"$PHP_SELF?offset=$last_row&$url_str\" class=\"$class\">LastPage</a> | ";
}
}
elseif ($mod == "2") {

$str2 = "";
$i = ceil($current_page / 10 ) - 1 ;

if ($i >= 1 ) {
$of = max(0, $offset - ( $limit_row * 10)) ;
$str2.= "<a href=\"$PHP_SELF?offset=$of&$url_str\" class=\"$class\">上10頁</a> ";
}
$a=min($total_pages, ($i*10)+10);
for ($i = 1+($i*10); $i <= $a; $i++) {
$of = $i * $limit_row - $limit_row;
if ($i == $current_page)
$str2.= "[ $i ] ";
else
$str2.= "<a href=\"$PHP_SELF?offset=$of&$url_str\" class=\"$class\">$i</a> ";
}
if ($i < $total_pages ) {

$of = min($total_rows, $offset + ( $limit_row * 10));
$str2.= "<a href=\"$PHP_SELF?offset=$of&$url_str\" class=\"$class\">下10頁</a>";
}
}
else {
$str2 = "Page:";
for ($i =1; $i <= $total_pages; $i++) {
$of = $i * $limit_row - $limit_row;
if ($i == $current_page)
$str2.= "[ $i ] ";
else
$str2.= "<a href=\"$PHP_SELF?offset=$of&$url_str\" class=\"$class\">$i</a> ";
}

}
return "<span class=$class>$str2</span>";
}

備註:
  • $conn 是 adodb 的object
    如果你沒有使用adodb
    你應該是要改成

    $mrows = $conn->Execute("select count(a_account) as T from $TABLE_NAME $WHERE_STR ");
    $mrow = $mrows->FetchObject();
    $numrows = $mrow->T;
    上面這三行程式.

    你要改成下面


    $mrows = mysql_query("select count(a_account) as T from $TABLE_NAME $WHERE_STR);
    $mrow = mysql_fetch_object($mrow);
    $numrows = $mrow->T;
  • $mrow = mysql_fetch_object($mrow); 裡面是放$mrows
TOP

[C#] MS Chart Line

         private void CreateChart(DataTable dt)
        {
            // xValues 為日期; yValues 為點擊數量;
            string[] xValues = new string[dt.Rows.Count];
            int[] yValues = new int[dt.Rows.Count];

            int rowCount = 0;
            foreach (DataRow row in dt.Rows)
            {
                xValues[rowCount] = row["Date"].ToString();
                yValues[rowCount] = Convert.ToInt32(row["Count"]);
                rowCount++;
            }

            Chart1.Legends.Add("Legends1"); //圖例集合說明
            Chart1.Legends["Legends1"].DockedToChartArea = "ChartArea1"; //顯示在圖表內
            //Chart1.Legends["Legends1"].Docking = Docking.Bottom; //自訂顯示位置
            Chart1.Legends["Legends1"].BackColor = Color.FromArgb(235, 235, 235); //背景色
            //斜線背景
            Chart1.Legends["Legends1"].BackHatchStyle = ChartHatchStyle.DarkDownwardDiagonal;
            Chart1.Legends["Legends1"].BorderWidth = 1;
            Chart1.Legends["Legends1"].BorderColor = Color.FromArgb(200, 200, 200);



            Chart1.ChartAreas["ChartArea1"].AxisY.ScaleBreakStyle.CollapsibleSpaceThreshold = 20;
            Chart1.ChartAreas["ChartArea1"].AxisY.ScaleBreakStyle.LineColor = Color.Red;
            Chart1.ChartAreas["ChartArea1"].BackGradientStyle = GradientStyle.VerticalCenter;

            //3D設定
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = false; //3D效果
            //Chart1.ChartAreas["ChartArea1"].Area3DStyle.IsClustered = true; //並排顯示
            //Chart1.ChartAreas["ChartArea1"].Area3DStyle.Rotation = 40; //垂直角度
            //Chart1.ChartAreas["ChartArea1"].Area3DStyle.Inclination = 50; //水平角度
            //Chart1.ChartAreas["ChartArea1"].Area3DStyle.PointDepth = 30; //數據條深度
            //Chart1.ChartAreas["ChartArea1"].Area3DStyle.WallWidth = 0; //外牆寬度
            //Chart1.ChartAreas["ChartArea1"].Area3DStyle.LightStyle = LightStyle.Realistic; //光源

            Chart1.ChartAreas["ChartArea1"].BackColor = Color.FromArgb(240, 240, 240); //背景色
            //Chart1.ChartAreas["ChartArea1"].AxisX.Enabled = AxisEnabled.False; //隱藏 X 標示
            //Chart1.ChartAreas["ChartArea1"].AxisY.Enabled = AxisEnabled.False; //隱藏 Y 標示
            Chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.Enabled = false;   //隱藏 X 軸線
            //Chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.Enabled = false;   //隱藏 Y 軸線


            //Y 軸線顏色
            Chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.LineColor = Color.FromArgb(150, 150, 150);
            //X 軸線顏色
            Chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.LineColor = Color.FromArgb(150, 150, 150);

            // 讓 X 軸的座軸值能完全 show 出來
            Chart1.ChartAreas["ChartArea1"].AxisX.IntervalAutoMode = IntervalAutoMode.VariableCount;
            Chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.IsStaggered = false;
            // 讓 Y 軸的座軸值能完全 show 出來
            //Chart1.ChartAreas["ChartArea1"].AxisY.IntervalAutoMode = IntervalAutoMode.VariableCount;
            //Chart1.ChartAreas["ChartArea1"].AxisY.LabelStyle.IsStaggered = false;
            Chart1.Series["Series1"].Legend = "Legends1";
            Chart1.Series["Series1"].IsValueShownAsLabel = false; //顯示數據

            //設定 Series1-----------------------------------------------------------------------
            Chart1.Series["Series1"].Points.DataBindXY(xValues, yValues); // 利用 DataBindXY 分別把數列的 X 及 Y 值繫結至不同的來源
            Chart1.Series["Series1"].LegendText = "Hits";
            //Chart1.Series["Series1"].LabelFormat = "#,###"; //金錢格式
            //顯示X軸資料
            //Chart1.Series["Series1"].LegendText = "#VALX";
            //顯示Y軸資料
            //Chart1.Series["Series1"].Label = "#VALY";

            //圖型
            Chart1.Series["Series1"].ChartType = SeriesChartType.Line;
            //Chart1.Series["Series1"].Color = Color.Blue;
            //Chart1.Series["Series1"].IsValueShownAsLabel = true;

            //字體顏色設定
            //Chart1.Series["Series1"].LabelForeColor = Color.Red;
            //Chart1.Series["Series1"].MarkerBorderColor = Color.Silver;
            //字體設定
            Chart1.Series["Series1"].Font = new System.Drawing.Font("Trebuchet MS", 10, System.Drawing.FontStyle.Bold);
            Chart1.Series["Series1"].BorderColor = Color.FromArgb(255, 101, 101, 101);
            //數值顯示在圓餅外
            //Chart1.Series["Series1"]["PieLabelStyle"] = "Outside";
            //設定圓餅效果,除 Default 外其他效果3D不適用
            ////Chart1.Series["Series1"]["PieDrawingStyle"] = "Default";
        }

參考資料:
MS Chart Control 學習手記(二) - 圓餅圖
http://www.dotblogs.com.tw/suehilary/archive/2011/10/24/46163.aspx
[修練營_MSChart, C#][005] 簡易的圖表「複製」功能
http://www.dotblogs.com.tw/nobel12/archive/2009/12/31/12750.aspx

ASP.NET 3.5 Chart Code With C# 使用範例
http://www.wretch.cc/blog/jakeuj/16431027
[立体,3D]MS Chart Control 學習手記(一) - 直條圖&橫條圖
http://www.cnblogs.com/-clq/archive/2012/02/09/2344273.html
C# Asp.net chart的圖表設定方式
http://fongzih.blogspot.tw/2011/09/c-aspnet-chart.html
[ASP.NET] MS Chart (2)
http://www.dotblogs.com.tw/shunnien/archive/2013/04/22/102049.aspx

MS Chart Control 學習手記(一) - 直條圖&橫條圖(這篇寫的非常的好)
http://www.dotblogs.com.tw/suehilary/archive/2011/10/22/45430.aspx

chart鼠标悬停时显示数据和checkBox的默认状态
http://blog.csdn.net/lllljz/article/details/7616935

C#chart柱形图时,如何设置可以在柱子顶上显示数值
http://bbs.csdn.net/topics/390522713?page=1#post-395081594

TOP

[C#] DataView RowFilter null 清除RowFilter的條件

RowFilter 完之後,如果需要再調用該Dataview的資料,要記得將RowFilter資料清除。

//利用RowFilter 去查詢需要的資料
dv.RowFilter = string.Format("Date = '{0}'", startDate.ToString("yyyy/MM/dd"));

//清除RowFilter的條件
dv.RowFilter = null;

如果沒有清除RowFilter的條件,使用dv時的資料,都只會有條件式下的資料。
TOP

[C#]DataView string and int sort 字串及數值排序

原本的Count為文字型態,在排序時會遇到排序不正確的問題。
因此需增加一個數字型態,再依數字型態排序。

//資料來源 DataSet
DataTable dt = ds.Tables["Log"];

//增加newCount欄位型態為Int32,資料來源從Count取得。
dt.Columns.Add("newCount", typeof(int), "Convert(Count,'System.Int32')");

//將資料轉存至DataView
DataView dv = dt.DefaultView;

//依數字型態提供排序使用
dv.Sort = "newCount DESC";

參考資料:http://blog.csdn.net/lin304510260/article/details/7852518
TOP

[C#]DataTable Top 10 Data 取10筆資料

//DataTable的資料來源 DataSet
DataTable dt = ds.Tables["Data"];

//建立一個新的DataTable dtTop10,並且將dt內10筆資料copy至dtTop10內。
//Take(10)就表示10筆。
DataTable dtTop10 = dt.Rows.Cast<DataRow>().Take(10).CopyToDataTable();

參考資料:
http://www.aspforums.net/Threads/550065/Get-Top-N-Rows-from-Datatable-or-DataSet-in-C/
TOP

[C#]DataTable New Row 新增一筆資料

//建立一個新的Datatable
DataTable dt = new DataTable();

//從DataSet取得資料,並存至DataTable的dt內
dt = ds.Tables["Data"];

//建立一筆新的DataRow,並且等於新的dt row
DataRow row = dt.NewRow();

//指定每個欄位要儲存的資料
      row["Date"] = startDate.ToString("yyyy/MM/dd");
      row["Count"] = "0";

//新增資料至DataTable的dt內
 dt.Rows.Add(row);    

參考資料:http://social.msdn.microsoft.com/Forums/zh-TW/07dda425-e1b7-4202-8fca-31c3c31a0159/datatable-

http://edward.msize.tw/2010/11/c-data-table.html
TOP

[JavaScript]利用JavaScript控制INPUT type=file ,disabled 或是visible,並清除INPUT type=file資料

因為需求希望使用radiobuttonlist控制上否上傳「預設檔案」或是「自傳檔案」

<asp:radiobuttonlist id="Upload" runat="server" RepeatLayout="Flow" RepeatColumns="2" RepeatDirection="Horizontal">
<ASP:LISTITEM Value="0" Selected="True"></ASP:LISTITEM>
<ASP:LISTITEM Value="1"></ASP:LISTITEM>
</asp:radiobuttonlist>

<INPUT id="cmdBrowse" type="file" size="40" name="cmdBrowse" runat="server">


<script language="javascript">
    function ChangeUpload() {
        rdlUpload = document.getElementById("Upload");
        if (rdlUpload .checked) {
             //有兩種方式可以控制或隱藏
             //(1)disabled 
            document.getElementById("cmdBrowse").disabled = "disabled";    
             //(2)visible
            document.getElementById("cmdBrowse").style.visibility = "hidden";
            //清除INPUT  type="file"的資料
            ClearUpload();
        } else {
             //(1)取消visible
             document.getElementById("cmdBrowse").style.visibility = "visible";
             //(2)取消disabled
             document.getElementById("cmdBrowse").disabled = "";
        }
    }

     //清除INPUT  type="file"的資料
     function ClearUpload() {
        var InputFile = document.getElementById("cmdBrowse");
        InputFile.outerHTML = InputFile.outerHTML.replace(/value=\w/g, '');
    }
</script>

c#的程式要加上onClick時觸法javascript的ChangeUpload()

rdlUpload.Attributes.Add("onClick", "javascript:ChangeUpload()")
TOP

[ASP.NET] System.IO.File(判斷檔案是否存在、刪除、覆製、覆蓋)

判斷檔案是否存在
If (System.IO.File.Exists("C:\1.txt")) Then

End if

刪除C:\1.txt
System.IO.File.Delete("C:\1.txt")

覆製檔案,如果有相同檔名直接覆蓋
System.IO.File.Copy("D:\1.txt", "C:\1.txt", True)
TOP

[Javascript] 利用Attributes增加onBlur及onFocus,顯示欄位未輸入資料前的預設值


 利用Attributes增加onBlur及onFocus,顯示欄位未輸入資料前的預設值
_Name = "ABC"
Name.Text = _Unnamed
Name.Attributes.Add("onBlur", "javascript: if (this.value=='') this.value='" & _Name& "';")
Name.Attributes.Add("onFocus", "javascript: if (this.value=='" & _Name& "') this.value='';")
TOP

[Javascript] 清空 Input File值

清空 Input File值

Input File因為安全性的關系,沒有辨法設定他的值,但可以清空他的值


function Clear(){
var InputFile = document.getElementById("InputFile");

InputFile.outerHTML = InputFile.outerHTML.replace(/value=\w/g, '');
}

<upload:InputFile id="InputFile" runat="server"></upload:InputFile>
TOP

[ASP.NET] regular expressionvalidator 排除 特定符號


有的時後某些欄位希望使用者不可以輸入特定的文字或符號。就可以使用 \b((?!>|<)\w)+\b

Ex:利用regularexpressionvalidato排除 大於 >及小於 < 兩個符號。

<asp:regularexpressionvalidator id="NameFormat" runat="server" cssclass="NormalRed"  controltovalidate="txtName" display="Dynamic" validationexpression="\b((?!>|<)\w)+\b"></asp:regularexpressionvalidator>
TOP

[ASP.NET] User輸入資料的編碼方法

就如文章所說初學的工程師真的不會考慮到編碼的方式及問題
特別是以前寫Windows Form 跳到Web Form。

當輸入的資料

Ex: 如果使用者在TextBox輸入<b>Test</b>
在HTML輸出時,會直接變成 Test  <==他變粗體了
所以要利用Server.HtmlEncode轉回成原本輸入的純文字
Server.HtmlEncode(abc)

但在變為純文字時又會遇到一個狀況,那User真的按了一個斷行怎辨~~
利用Replace把他轉為真的斷行


Ex: 如果使用者在TextBox輸入
<b>Test</b><b>Test</b>
<b>Test2</b>
<b>Test3</b>
Server.HtmlEncode(abc).Replace(vbCrLf, "<br />")

參考資料:http://blog.miniasp.com/post/2008/11/Explain-web-related-encoding-decoding-method-in-detail.aspx
TOP

[ASP.NET] 用Server.HtmlEncode() 防止TextBox輸入HTML TAG,且可以換行

用Server.HtmlEncode() 防止TextBox輸入HTML TAG,且可以換行

DIM Description = "XXXXXXXXXX"
Server.HtmlEncode(Description).Replace(vbCrLf, "<br />")
TOP

[ASP.NET] User填寫純數字時全形及半形的處理


跟上一篇一樣這個真的是一個非常麻煩的東西,在純數字欄位的時後判斷全形及半形時該如何處理。

最快的方式是讓User輸入的資料,全部轉為半形。

因為需求是要在資料輸入前先做好驗證,所以利用RangeValidator加上validationexpression去處理。

1.限制validationexpression="\d*"只能輸入數字。

<asp:textbox id="Word" runat="server" maxlength="6" size="12"></asp:textbox>
<asp:regularexpressionvalidator id="valWord" runat="server"  controltovalidate="txtWordUser" display="Dynamic" validationexpression="\d*">
</asp:regularexpressionvalidator>

2.限制最大至最少的數字。
<asp:RangeValidator ID="valWordUserFormat" runat="server" display="Dynamic"
controltovalidate="txtWordUser" MinimumValue="1" MaximumValue="999999" Type="Integer"></asp:RangeValidator>


TOP

[ASP.NET] User填寫資料時全形及半形的處理

遇到一個非常麻煩的東西,User輸入的資料如果有全形及半形時該如何處理。

最快的方式是讓User輸入的資料,全部轉為半形。

全形轉半形

VbStrConv.Narrow :全形轉半形


 Dim Word As String
 Dim NewWord As String
Word  = "ABC"  

NewWord  =  StrConv(Word , VbStrConv.Narrow)

半形轉全形
VbStrConv.Wide:半形轉全形


 Dim Word As String
 Dim NewWord As String
Word  = "ABC"  

NewWord  =  StrConv(Word , VbStrConv.Wide)


參考資料:http://www.dotblogs.com.tw/hatelove/archive/2009/04/02/7810.aspx


TOP

[C#]Get DataView Value(取DataView欄位資料)


取得DataView欄位資料的方式:

        DataView dv  = new DataView();
        dvOrgMapping = GetData() //在GetData裡面取得資料

        如果要取某一Row內的Name欄位的值

        dv.Table.Rows[i]["Name"].ToString()
        也可以寫成
        dv[0]["Name"].ToString()

        兩個方式是一樣的。

參考資料:http://wangshifuola.blogspot.tw/2010/11/aspnetdataviewindex.html
TOP

[C#]初學Class,如何建立一個簡單的Class,以及field,property的差別。



初學者最常遇到的一個狀況,知道怎麼使用別人已經建立好的Class,但不知道該如何自已建立一個新的Class。
該如何建立一個簡單的Class,以及field,property的差別。

1.先建立一個新的UserDataModel.cs。
(1)新增一層UserDetailModel的class,且使用field/欄位的方式。


public class UserDataModel
{
    public class UserDetailModel
    {
        public string account;
        public string firstName;
        public string lastName;
        public DateTime createDate;
        public string createUser;
    }
}


(2)property/屬性的方式。


public UserDataModel
{
    private DateTime _myBirthday


    public DateTime myBirthday
    {
        get
        {
                return _myBirthday;
        }
        set
        {
            if (Value <= DateTime.UtcNow)
           {
              _myBirthday = Value;
           }
           else
           {
              throw new Exception("Birthday Fail.")
           }
        }
    }


}

(3)property/屬性的方式,將資料存在Session內。

    public static string account
    {
        get
        {
            if (HttpContext.Current.Session["account"] == null)
                return string.Empty;
            else
                return HttpContext.Current.Session["account"].ToString();
        }
        set
        {
            HttpContext.Current.Session["account"] = value;
        }
    }

2.如何將資料存入Class內,使用前一定要先New Class。


    protected void Page_Load(object sender, EventArgs e)
    {

       UserDataModel.UserDetail = SetUser ();
    }


    public static UserDataModel.UserDetailModel SetUser ()
    {

        UserDataModel.UserDetailModel myUser = new UserDataModel.UserDetailModel();
        myUser.account = "UserAccount";
        myUser.firstName= "ABC";
        myUser.lastName= "DEF";
        myUser.createDate= "account";
        myUser.createUser= "ABC";
        return myUser;
    }

參考資料:
http://www.allenkuo.com/EBook5/view.aspx?a=1&TreeNodeID=123&id=279
http://www.allenkuo.com/EBook5/view.aspx?a=1&TreeNodeID=123&id=969



TOP

[C#] Key Value Collection(NameValueCollection、SortedList、Dictionary)

Key Value Collection最重要的用法就是利用Key及值去儲存想要的資料
因為在C# 3.5版本內沒有提供Optional 參數的功能,如果要傳送不固定參數時,會很麻煩。
因此利用Collection的方式記錄參數,就不用擔心非固定參數傳值的問題。

using System.Collections.Specialized;


protected void Page_Load(object sender, EventArgs e)
        {


            NameValueCollection nvc = new NameValueCollection();
            nvc.Add("FirstName", "ABC");
            nvc.Add("LastName", "DEF");
            nvc.Add("Phone", "123456789");
            nvc.Add("Status", "10");

           UpdateNvcData(nvc);
    }

 
public static string UpdateNvcData(NameValueCollection nvc)
    {

       foreach (string i in nvc.Keys)
          {
            Console.WriteLine("Key:{0}", i)
            Console.WriteLine("Value:{0}",  nvc.GetValues(i))
           }

    }



NameValueCollection
參考資料:
http://www.dotblogs.com.tw/yc421206/archive/2009/04/06/7886.aspx

SortedList
參考資料:
http://msdn.microsoft.com/zh-tw/library/system.collections.sortedlist(VS.80).aspx
http://www.dotblogs.com.tw/chris0920/archive/2010/03/24/14205.aspx

Dictionary
參考資料:
http://blog.csdn.net/sunnykaho/article/details/4435568
TOP

[C#] C# 4.0 Optional Parameters VS C#3.5 SortedList 替代Optional Parameters (變動參數)

很殘酷的問題,因為無法將專案升級到C#4.0 (VS2010)開發的原因,造成最新的 Optional Parameters功能無法使用,只好找替代方案解決這個問題。

C#3.5未提供Optional Parameters的方式,因此使用SortedList的方式輸入參數值。


            SortedList mySL = new SortedList();
            mySL.Add("First", "Hello");
            mySL.Add("Second", "World");
            mySL.Add("Third", "!");
            PrintKeysAndValues(mySL);


        public static void PrintKeysAndValues(SortedList myList)
        {
            Console.WriteLine("\t-KEY-\t-VALUE-");
            for (int i = 0; i < myList.Count; i++)
            {
                Console.WriteLine("\t{0}:\t{1}", myList.GetKey(i), myList.GetByIndex(i));
            }
            Console.WriteLine();
        }



參考資料:
http://msdn.microsoft.com/zh-tw/library/system.collections.sortedlist(VS.80).aspx
http://www.dotblogs.com.tw/chris0920/archive/2010/03/24/14205.aspx

C# 4.0 Optional Parameters 
參考資料:
http://www.dotblogs.com.tw/larrynung/archive/2009/07/29/9720.aspx


相同的變動參數,但如果是不清楚有多少個相同的參數要輸入,就可以使用這個方法。

public static void Main()
{
   ShowName("ABC");
   ShowName("ABC", "DEF");
}

public static void ShowName(params string[] names)
{
   foreach (string name in names)
   {
     Console.WriteLine(name);
    }
}
一維的變動參數參考資料:
http://tw.myblog.yahoo.com/coolong_chen/article?mid=240
TOP

[C#]用txt增加Exception Log檔(FileStream,StreamReader,StreamWriter)

因為系統一直出現無法理解的Exception ,因此增加Exception 的模組來記錄。
string ExceptionFileName = "D:\\Exception.txt";
//利用File.Exists判斷是否已經存在該檔案

        if (!File.Exists(ExceptionFileName))
        {
            //利用StreamWriter就可以新增一個txt檔,並且將Exception的資料填寫至txt檔內。
            using (StreamWriter sw = File.CreateText(ExceptionFileName))
            {
                sw.WriteLine("Message={0}。", message);
                sw.Close();
            }
        }
        else
        {
            //已經有這個檔案,因此只開啟這個檔案
            using (StreamWriter sw = new StreamWriter(ExceptionFileName))
            {

                sw.WriteLine("Message={0}。", message);
                sw.Close();

            }
        }


但在這裡就會遇到一個問題了,每次log都會被覆蓋,只保留最後一次的log而已。
因此換另一個方式來處理。

先讀取檔案內的資料。

FileStream FsRead = File.Open(ExceptionFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamReader Sreader = new StreamReader(FsRead);
string strSr = Sreader.ReadToEnd();
Sreader.Dispose();
FsRead.Dispose();

將讀取出來的資料加上新的錯誤訊息,再回寫至原檔案內。

FileStream FsWrite = File.Open(ExceptionFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamWriter Swriter = new StreamWriter(FsWrite);
Swriter.WriteLine("{0}", strSr);
Swriter.WriteLine("Message={0}。", message);
Swriter.Dispose();
FsWrite.Dispose();

參考資料:http://dnowba.blogspot.tw/2012/07/streamwriter-io.html
http://www.dotblogs.com.tw/yc421206/archive/2009/01/18/6862.aspx

補充:
也可以利用FileMode.Append直接從檔案的最後加上要填寫的資料。

        FileStream FsWrite = File.Open(ExceptionLogFileLocation, FileMode.Append);
        StreamWriter Swriter = new StreamWriter(FsWrite);
        Swriter.WriteLine("Message={0}。", message);
        Swriter.Dispose();
        FsWrite.Dispose();

http://www.dotblogs.com.tw/yc421206/archive/2009/01/18/6862.aspx

TOP

[C#]Select Data into DataView from Database


解決從SQL取得資料後無法直接存至DataView,需從DataSet轉至DataView

SqlConnection conn = new SqlConnection("");
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
string sqlstr = "select * from table";
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(sqlstr, conn);
DataSet ds = new DataSet();
da.Fill(ds);
DataView dv = ds.Tables[0].DefaultView;
conn.Close();
da.Dispose();
TOP

[Apple] iframe in ipad safari


目前在開發的程式是使用 的方式。

掛在別人的主機平台上使用產品,因此使用了iframe掛載。

結果遇到IOS6.1版本的 ipad 及 iphone 使用safari瀏灠器時 iframe不受控制的超過原本平台上的網頁寬度。

目前的解決方式是加上<Div>

<div id="scrollee" style="-webkit-overflow-scrolling:touch; overflow: scroll;">
 
 <iframe id="object" height="90%" width="100%" type="text/html" src="http://en.wikipedia.org/">
 </iframe>
</div>


參考網頁:
http://stackoverflow.com/questions/5267996/how-to-properly-display-an-iframe-in-mobile-safari


因為加入Div變成右在IE、Chrome、及Firefox右邊及下面都會多出 scroll
所以將右邊 Y軸Hidden起來,X軸不能Hidden,因為如果Hideen的話在touch上面就不能左右移動了。

<div style=”overflow-x:scroll ;overflow-y:hidden;overflow:-moz-scrollbars-horizontal !important;”></div>

參考網頁:
http://blog.xuite.net/linriva/blog/52358732-%5BCSS%5DDiv+with+Scroll+bar+~++%E8%BD%89%E8%B2%BC
TOP

[C#] Select Data into DataTable from Database


最主要是要將資料取得的資料存在DataTable。

SqlConnection conn = new SqlConnection("");
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
string sqlstr = "select * from " + strtable;
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(sqlstr, conn);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
da.Dispose();

參考資料:http://www.wretch.cc/blog/s0341969/33051318
TOP

[C#] Insert Data to DataBase with SQL Parameter

使用Parameter 最主要的原因是為了防止SQL Injection

SqlConnection conn = new SqlConnection("");
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
string strSql = "insert into Table (Name,Id)";
strSql += "VALUES (@Name, @Id)";
conn.Open();
SqlCommand sqlcom = new SqlCommand(strSql, conn);
sqlcom.Parameters.AddWithValue("@Name", Name);
sqlcom.Parameters.AddWithValue("@Id", Id);
SqlDataReader sqldr = sqlcom.ExecuteReader();
sqldr.Close();
conn.Close();
TOP

[C#]SQL Parameter defense SQL injection

最容易被SQL injection 的語法如下:

SqlConnection conn = new SqlConnection("");
conn.ConnectionString =    System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
string sqlstr = "select * from table where name = '" + strName + "'";
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(sqlstr, conn);
conn.Close();
da.Dispose();

目前利用SQL Parameter 就可以避免此問題

SqlConnection conn = new SqlConnection("");
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
string strSql = "select * from table where Name=@Name";
conn.Open();
SqlCommand sqlcom = new SqlCommand(strSql, conn);
sqlcom.Parameters.AddWithValue("@Name", strName );
SqlDataReader sqldr = sqlcom.ExecuteReader();
sqldr.Close();
conn.Close(); 



TOP

[C#] Post Data With New Window - 2

前一篇Post資料的方式,會遇到一種狀況,當輸入或輸出的資料需要在Page_Load從資料庫或是其他的程式判斷之後才填寫,或是要使用DropDownList選擇項目再Post時,就會有點難題。

因為利用另外一個偷吃步的方式來達成相同的效果。


1.在要送資料的Page_Load內,建立Session儲存要傳送的資料,利用Window.open開啟PostData.aspx。

    protected void Page_Load(object sender, EventArgs e)
    {

            Session.Add("name", Name.Text.Trim());

            string strUrl = string.Format("{0}/PostData.aspx", ConfigurationManager.AppSettings["WebRootUrl"]);
            ScriptManager.RegisterStartupScript(this, this.GetType(),
                "recordOpenUrl",
                "window.open('" + strUrl + "','recordOpenUrl','" + "" + "');", true);

     }


2.建立一個新的PostData.aspx頁,準備讀取session資料,並且利用JavaScript自動submit該資料的form。


<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
<script language="JavaScript" type="text/javascript" defer>
    document.formid.submit()
</script>
   
</head>
<body>
    <form name="formid" method="post" action="https://www.streamwing-gridow.com/signup/sfdc">
        <div>
            <input id = "name"  type="hidden" name="first_name" value=" <%=Session["name"] %>" />
        </div>
    </form>
</body>
</html>


特別注意:此為自動送出資料的關鍵。

<script language="JavaScript" type="text/javascript" defer>
    document.formid.submit()
</script>

3.chrome及firefox的瀏覽器上執行此JavaScript
要在body內加上onload
<body onload="document.formid.submit()">

TOP

[C#]Post Data With New Window

在C#內要傳送method為Post的資料至其他頁面,且還要是新的視窗。

1.主要還是利用javascript的方式做處理
放javascript方式有兩種

(1)直接將javascript放ASPX內的Head裡面
<head runat="server">

    <script type="text/javascript">    



 function openWindowWithPost(url, name, keys, values) { //開新視窗,這邊我不指定新視窗的網址
     var newWindow = window.open("", name, "height=700, width=600, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, status=no");
     if (!newWindow) return false;
     var html = "";
     html += "<html><head></head><body><form id='formid' method='post' action='" + url + "'>";
     if (keys && values && (keys.length == values.length))
         for (var i = 0; i < keys.length; i++)
         html += "<input type='hidden' name='" + keys[i] + "' value='" + values[i] + "'/>";
     html += "</form><script type='text/javascript'>document.getElementById(\"formid\").submit()</script></body></html>";
     newWindow.document.write(html);
     return newWindow;
 }

 function Post(url,title) { //這個function會把網頁中所有的form找出來,並且找出每個form所包含的elements
     var keys = [];
     var values = [];
     for (var i = 0; i < document.forms.length; i++) {
         for (var j = 0; j < document.forms[i].elements.length; j++) {
             if (document.forms[i].elements[j].name != undefined &&
                document.forms[i].elements[j].value != undefined) {
                 keys[keys.length] = document.forms[i].elements[j].name;
                 values[values.length] = document.forms[i].elements[j].value;
             }
         }
     }
     openWindowWithPost(url, title, keys, values);
 }
</script>
</head>

(2)
將javascript的程式放仙tools.js內,aspx看起來也比較乾淨。
<head runat="server">
    <script type="text/javascript" src="Js/tools.js"></script>
</head>

2.在C#的Codebehind程式碼內。
    protected void Page_Load(object sender, EventArgs e)
    {

      Page.RegisterStartupScript("Show", "<script language=\"JavaScript\">Post('網址','名稱');</script>");
    }

3.HTML內的輸入方式要改為input,不可以使用textbox,不然javascript會抓不到資料。
                <input id = "name"  type="text" name="name" value="name" />

參考資料:
http://www.dotblogs.com.tw/puma/archive/2008/09/03/5288.aspx
http://takamai.pixnet.net/blog/post/33804587-asp.net-%E9%85%8D%E5%90%88javascript%E9%96%8B%E6%96%B0%E8%A6%96%E7%AA%97%E4%B8%A6%E4%B8%94%E4%BD%BF%E7%94%A8post%E5%82%B3%E9%81%9E



TOP

[Share]撰寫程式的觀念

最近在寫程式的時後,一直被主管再教育撰寫程式的觀念

分享給大家這個觀念,有的時後觀念比會跑的程式還要重要!!!

目前Microsoft Visual Studio的程式已經開發至2012的版本,程式中使用到的的物件或屬性也越來越多且簡單,但也相對的因為越來越多,造成我常常只會使用熟悉的去撰寫程式。

1.時時要學習及注意官方改變的物件及屬性。

2.撰寫程式時要懂得先查詢本身物件是否已經提供屬性使用,不要像我常傻傻的去找有沒有什麼其他的物件可以來做,兜了一大圈浪費一堆時間。

3.確實瞭解PM的需求,且再次確認PM說的是否正確,因為常常發生PM或測試工程師說的狀況跟工程師測出來的結果不相同。

4.撰寫程式時,需要考慮到每一個可能造成程式的錯誤的原因。
   我想應該有人會說這不是廢話嗎!!
拿個例子來說:如果程式要從web.config取得某一個預設資料時,又因為人的疏忽在Web.config的預設值沒有加入該數值,造成程式抓不到資料時所造成的錯誤!


TOP

[C#]GridView 排序及箭頭方向

不使用SqlDataSource的Sorting方式

因為資料來源不是從SqlDataSource取得,所以Sorting的時後要自已用ViewState去記錄選擇的是那個LinkButton及方向,如果使用SqlDataSource就不會有這個問題。

<asp:GridView ID="GridView1" runat="server"
                        onrowdatabound="GridView1_RowDataBound" AllowPaging="True"
                        onpageindexchanging="GridView1_PageIndexChanging"
                        AutoGenerateColumns="False"
                        CellPadding="4" AllowSorting="true"
                        onsorting="GridView1_Sorting"
                        onrowcreated="GridView1_RowCreated">
</asp:GridView>




 protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            foreach (TableCell tc in e.Row.Cells)
            {
                if (tc.HasControls() == true)
                {
                    if (((LinkButton)tc.Controls[0]).Text == "Duration")
                    {
                        ((LinkButton)tc.Controls[0]).Text = GetLocalResourceObject("Duration").ToString();
                    }
                    else if (((LinkButton)tc.Controls[0]).Text == "RecordingName")
                    {
                        ((LinkButton)tc.Controls[0]).Text = GetLocalResourceObject("RecordingName").ToString();
                    }
                    else if (((LinkButton)tc.Controls[0]).Text == "FileSize")
                    {
                        ((LinkButton)tc.Controls[0]).Text = GetLocalResourceObject("FileSize").ToString();
                    }

                    if (((LinkButton)tc.Controls[0]).CommandArgument == ViewState["SortDir"].ToString())
                    {
                        if (ViewState["mySorting"].ToString() == "ASC")
                        {
                            tc.Controls.Add(new LiteralControl("↓"));
                        }
                        else
                        {
                            tc.Controls.Add(new LiteralControl("↑"));
                        }
                    }
                }
            }
        }


    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (ViewState["mySorting"] == null)
        {
            e.SortDirection = SortDirection.Ascending;
            ViewState["mySorting"] = "ASC";
        }
        else
        {
            if (ViewState["mySorting"].ToString() == "ASC")
            {
                e.SortDirection = SortDirection.Descending;
                ViewState["mySorting"] = "DESC";
            }
            else
            {
                e.SortDirection = SortDirection.Ascending;

                ViewState["mySorting"] = "ASC";
            }

            ViewState["SortDir"] = e.SortExpression;
        }
        GetGridView1Data();
    }

TOP

[C#]取得兩個字串之間的字串



string strNewWord = "";
string strWord = "<ABC>WORD</ABC>";

//取得兩個字串之間的字串
strNewWord = strWord.Split(new String[] { "</ABC>", "<ABC>" });

TOP

[C#]取得.Net 3.5 ListView 樣版內的欄位值方式

取得.Net 3.5 ListView 樣版內的欄位值方式





<asp:ListView ID="ListView1" runat="server" style="font-size: small"
     onitemdatabound="ListView1_ItemDataBound">
     <ItemTemplate>
 <asp:Label ID="label1 e" runat="server"></asp:Label>  
     </ItemTemplate>
</asp:ListView>

    protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
//先將e.Item存放至 dataItem內
        ListViewDataItem dataItem = (ListViewDataItem)e.Item;
//利用FindControl取得欄位資料
        Label label1 = (e.Item.FindControl("label1") as Label);
//將取得listview內label1的資料存至strlabel1
        string strlable1 = DataBinder.Eval(dataItem.DataItem, "label1").ToString();
    }




參考資料:http://iambigd.blogspot.tw/2010/07/listview-itemdatabound.html
TOP

[C#]取得該頁QueryString的屬性方式

取得單一個QueryString的方式

string strConferenceID = Request["ConferenceID"];

取得一整串QueryString的方式

QueryStr = this.Page.ClientQueryString;


    public string QueryStr
    {
        get
        {
            return (string)ViewState["QueryStr"];
        }
        set
        {
            ViewState["QueryStr"] = value;
        }

    }
TOP

[C#]3.5以下的版本GridView無資料時顯示Header


VS2008為 .Net 3.5版本,還沒有支援GridView無資料時顯示Header的屬性
利用障眼法的方式達成相同功能,雖然不是很好,但比較簡單。

1.建立一個新的DataTable
            DataTable dtDataTemp = new DataTable();
            dtDataTemp.Columns.Add("名稱");
            dtDataTemp.Columns.Add("名稱");

2.建立一個新的DataView 並且設定來源為DataTable
            DataView dvDataTemp = dtDataTemp.DefaultView;

3.設定一筆新的DataRow 資料
            DataRow oDR = dvDataTemp.Table.NewRow();

4.允許資料列的欄位可以是DBNULL值
            foreach (DataColumn item in oDR.Table.Columns)
            {
                item.AllowDBNull = true;
            }

5.Datatable 加入資料列
            dvDataTemp.Table.Rows.Add(oDR);

6.GridView設定來源資料及DataBind
            GridView1.DataSource = dvDataTemp;
            GridView1.DataBind();

7.隱藏第一筆資料
            GridView1.Rows[0].Visible = false;

參考資料:
http://kuomingwang.blogspot.tw/2010/03/c-datatable-datagridview.html
http://stackoverflow.com/questions/2040107/show-header-of-a-empty-gridview-for-datasource-is-listdata
http://blog.sina.com.tw/jspcity/article.php?pbgid=55389&entryid=576147
http://www.dotblogs.com.tw/atowngit/archive/2010/08/12/17160.aspx
TOP

[C#]DataSet 資料存到Datatable

        DataTable dt = ds.Tables["資料表名稱"];
TOP

[C#]GridView內的DropDownList當Button方式使用

GridView內的DropDownList當button方式使用

這不是一個很好的使用方式,選取DropDownList值時模擬Button的事件或執行JavaScript使用。
最好不要這樣子使用,真的會被搞死。

以下遇到的方式都是需要用JavaScript去模擬的或控制

1.DropDownList選擇第1個值時,需要利用JavaScript開啟新的一頁,並將資料傳送過去。

使用ScriptManager.RegisterStartupScript方式呼叫JavaScript


strResult = "網址及參數值";

string newWindowSet = "height=600,width=800,toolbar=no,menubar=no,scrollbar=yes,location=yes,directories=no";

ScriptManager.RegisterStartupScript(this, this.GetType(), "名稱",
                "window.open('" + strResult + "','名稱','" + newWindowSet + "');", true);


2.DropDownList選擇第2個值時,需要有confirm的對話視窗讓使用者選擇「Yes」或「No」,才可以執行事件。
目前我找不到DropDownList可以這樣子處理的方式,因為DropDownList只能對一個物件做控制,不能對每一個值做onclick或onchange的控制,因此建立一個Button去模擬相同的功能。
且因為要使用Button的功能,不能用Visible= flase關閉button,所以只能將Button在畫面隱藏起來。

<span style="DISPLAY:none">
 <asp:Button ID="btnDel" runat="server" CausesValidation="false"      Text="Delete"
                                        OnClientClick='return confirm(this.getAttribute("RecordDelMessage"))'
                                        onclick="btnDel_Click" />
</span>

ScriptManager.RegisterStartupScript(Page, Page.GetType(), "btn_Del", "{ document.getElementById('" + btnDel.ClientID + "').click();}", true);

利用ScriptManager.RegisterStartupScript方式呼叫JavaScript執行btnDel的click,觸發OnClientClick的事件。

參考資料:
http://felixhuang.pixnet.net/blog/post/24392024-%5Bjavascript%5D-%E7%94%A8-javascript-%E5%9F%B7%E8%A1%8C-asp.net-server-button-(
http://king971119.blogspot.tw/2011/08/jquery-javascript-button-click.html
http://www.cnblogs.com/wzg0319/archive/2011/03/25/1995772.html
http://www.wretch.cc/blog/theone114/21735441
http://blog.yam.com/wewa85/article/29059195
TOP

[C#]GridView不使用SQLDataSource取得資料且分頁

手上的案子因為使用API取得資料來源,所以無法使用精靈或是SQL語法取得資料來源。
因此需要在不使用SQLDataSource精靈的方式完成GridView的資料分頁
1.先從ToolBox內的Data將GridView連至ASPX的網頁上。

2.在Properties內將AllowPaging設定為True,PageSize為每頁要顯示幾筆資料。



3.在Events內將點擊PageIndexChanging,加入程式碼。

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataSource = GetSource();
        GridView1.DataBind();
    }





 GetSource()為資料來源




TOP

[C#]隱藏GridView欄位

隱藏GridView欄位的方法:



    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //隱藏標題行


        if ( e.Row.RowType == DataControlRowType.Header)
        {
          e.Row.Cells[0].Visible = false;
        }


        //隱藏資料欄位

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
           e.Row.Cells[0].Visible = false;
        }

    }



TOP

[C#]DataSet 欄位及資料行的屬性使用方式

DataSet 欄位及資料行的屬性使用方式

AllowDBNull 取得或設定值,指出對於屬於資料表的資料列而言,這個資料行中是否允許 Null 值。
AutoIncrement取得或設定值,指出對於加入至資料表的新資料列而言,該資料行是否自動遞增資料行的值。
Caption 取得或設定資料行的標題。
ColumnName取得或設定在 DataColumnCollection 中的資料行名稱。
DataType 取得或設定儲存在資料行中的資料型別。
DefaultValue在建立新資料列時,取得或設定資料行的預設值。
MaxLength取得或設定文字資料行的最大長度。
Ordinal取得在 DataColumnCollection 集合中的資料行位置。
ReadOnly取得或設定值,指出是否資料列一加入至資料表,就允許變更資料行。
Unique取得或設定值,指出在資料行之每個資料列中的值是否必須是唯一的。

範例語法:
s = s.Replace("__範例1__", ""+ds.Tables["t"].Columns[i].ColumnName );
s = s.Replace("__範例2__", ""+ds.Tables["t"].Columns[i].DataType );

全部讀出欄位名稱:
string 暫存= "";
foreach (DataColumn Columns in ds.Tables["t"].Columns)
{
暫存 = 暫存 + Columns.ColumnName + "," ;

}

資料來源:http://note.jhpeng.com/2008/05/c_7734.html 


DataSet 取值

DataSet.Table[0].Rows[ i ][ j ]
其中 i 代表第 i 行數, j 代表第 j 列數

DataSet行數

DataSet.Table[0].Rows[ i ].ItemArray[ j ]
其中 i 代表第 i 行數, j 代表第 j 列數

DataSet列數

DataSet.Tables[0].Columns.Count
取得表的總列數

DataSet總行數 


DataSet.Tables[0].Rows.Count
取得表的總行數

DataSet中取出特定值

DataSet.Tables[0].Columns[ i ].ToString()
取得表的 i 列名


TOP

[C#] 在C# codebehind執行JavaScript

問題:因為程式取得在Codebehind內取得JavaScript,而且還要在Codebehind內執行此段JavaScript的function


  • Page.ClientScript.RegisterClientScriptBlock
  • Page.ClientScript.RegisterStartupScript
  • Page.ClientScript.RegisterClientScriptInclude
string Script=@”function ShowName() 
var txt=document.getElementById(‘txtName’);
 alert(‘Your name is: ‘+txt.value);
 }”;

Page.ClientScript.RegisterClientScriptBlock(this.GetType(), “ShowName”, Script, true);


參考資料 :
http://blog.mdsohelrana.com/2008/06/14/how-to-add-javascript-at-runtime-using-c-in-aspnet-20/




另外一種方式是Codebehind呼叫前端的JavaScript


A.aspx
<script type="text/javascript">
   
    function Popup(msg)
    {
        alert('訊息視窗 = ' + msg);
    }

</script>

A.aspx.cs
Page.RegisterStartupScript("Show", "<script language=JavaScript>Popup('"+字串+"');</script>");



參考資料 :

http://www.dotblogs.com.tw/aquarius6913/archive/2010/11/09/19310.aspx


TOP

[C#]多國語系補充 GlobalResources vs LocalResources

問題:
從Java派的系統內取得的Culture資料,但Culture無法直接轉換使用,但在C#或ASP.NET裡面Culture又不能只用義大利語「 it」或日語「ja」,需要使用義大利語「 it-IT」或日語「ja-JP
並且要特別注意Java派使用「_」,C#跟ASP.NET是使用「-」

解決方式:


CultureInfo culture = new CultureInfo(LoginUserInfo.IdentityInfo.language.Replace("_", "-"));

Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentUICulture.IetfLanguageTag);

CultureInfo newculture = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentUICulture.IetfLanguageTag);

Thread.CurrentThread.CurrentUICulture = new CultureInfo(newculture.ToString());

參考資料:http://mobile.dotblogs.com.tw/alonstar/archive/09/08/5319.aspx
TOP

[C#]在js檔內取得c#的變數

問題:現在接手的專案用jQuery來做留言的字數限制及判斷,且到達上限時會發送alert的訊息,但目前專案要將他改為多國語系的方式,所以一定要傳送GlobalResource或是LocalResources的變數值。

解決的方式:
1.在usercontrols的檔案內(ascx檔案內)增加javascript

         <script language="javascript" type="text/javascript">

            var data =
            {
                alert: "<%=GetLocalResourceObject("jQueryalert").ToString()%>",              
            };                    
         </script>


2.在js的檔案內改為


var settings = jQuery.extend(
{
    //原本是寫死的文字
//alertText: "You have typed too many characters.", // Text in the alert message
   //改為變數取得文字
alertText: data.alert, // Text in the alert message
}, options );


參考資料:http://sls.weco.net/blog/shortlin/11-1%E6%9C%88-2012/16971
TOP

[ASP.NET] 強制使用者使用特定的多國語系

續前篇多國語系的設定方式

前篇說明了如何設定多國語系的方式,但還有另外一個方法就是利用程式強制限制使用者的語系

Ex:

(1)zh-TW 為繁體中文
(2)

VB.NET方式
Protected Overrides Sub InitializeCulture()

    System.Threading.Thread.CurrentThread.CurrentUICulture = New System.Globalization.CultureInfo("zh-TW")

End Sub

(3)
C#方式
    protected override void InitializeCulture()
    {

            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("zh-TW");
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("zh-TW");
     }


參考資料:
http://kelp.phate.org/2011/10/getglobalresourceobject.html

TOP

[C#]在OnClientClick時使用多國語系的方法

依前篇在ASP.NET使用多國語系都是使用App_GlobalResources及App_LocalResources這兩種方式
這次在C#專案內全部使用App_GlobalResources的方法呈現所有的多國語系

一般在ASPX內取得多國語系資料的方法有兩種
1.<%$ Resources:多國語系檔案名稱, 屬性名稱 %>
2.<%=GetGlobalResourceObject("多國語系檔案名稱", "屬性名稱").ToString()%>

這次遇到當使用LinkButton並且又要使用OnClientClick="return confirm('Finish');"
這種確認的跳出視窗時,以上兩種方法都沒有辨法使用!!

解決方式:
增加一個Message來記錄要使用的多國語系文字,再用getAttribute取得就可以。
Ex:
<asp:LinkButton ID="btnDel" delmessage="<%$ Resources:Salesforce, Delete_Program %>"  OnClientClick='return confirm(this.getAttribute("delmessage"))'

參考資料:
http://forums.asp.net/t/1094986.aspx/1