顯示具有 ASP.NET C# 標籤的文章。 顯示所有文章
顯示具有 ASP.NET C# 標籤的文章。 顯示所有文章

2013年5月28日 星期二

ASP.NET (C#) 陣列的操作

using System;
using System.Collections;

public partial class _00_Basic : System.Web.UI.Page 
{
    //當頁面正在載入時所要執行動作。
    protected void Page_Load(object sender, EventArgs e)
    {
        //====  建立陣列資料  ==============================================

        //宣告一維字串陣列並加入內容。(內容多少決定大小)
        string[] arrStringA = { "A1", "A2", "A3", "A4" };

        //宣告一維字串陣列並設定大小與加入內容。
        string[] arrStringB = new string[4];
        arrStringB[0] = "B1"; arrStringB[1] = "B2"; arrStringB[2] = "B3"; arrStringB[3] = "B4";

        //宣告一維陣列清單會依照增加項目的多少而動態調整大小。
        ArrayList arrltStringC = new ArrayList();
        arrltStringC.Add("C1"); arrltStringC.Add("C2"); arrltStringC.Add("C3"); arrltStringC.Add("C4");

        //宣告一維整數陣列並加入內容。(內容多少決定大小)
        int[] arrIntA = { 1, 2, 3, 4 };

        //宣告一維整數陣列並設定大小與加入內容。
        int[] arrIntB = new int[4];
        arrIntB[0] = 11; arrIntB[1] = 12; arrIntB[2] = 13; arrIntB[3] = 14;

        //宣告二維字串陣列並加入內容。(內容多少決定大小)
        string[,] arrStringD = { { "a1", "a2", "a3" }, { "b1", "b2", "b3" } };

        //將字串內容依照特定符號分割成為一維陣列元素。
        string strWords = "a1 a2,a3.b1:b2,c1";
        string[] arrStringE = strWords.Split(new Char[] { ' ', ',', '.', ':' });
       
        //將陣列內的元素順序反轉。
        //Array.Reverse(arrStringA);
        //將陣列內的元素排序
        //Array.Soft(arrStringA);
        //在陣列內使用二分搜尋法,尋找指定資料。(使用之前必須先用Array.Soft()方法排序過,找到資料會傳回該index值)
        //Array.BinarySearch(arrStringA, "A3");
        //在陣列內搜尋資料,找到傳回給索引值。
        //Array.IndexOf(arrStringA, "A3");
        //從arr1陣列拷貝i個元素至arr2陣列。
        //Array.Copy(arr1, arr2, i);

        //====  讀取陣列資料  ==============================================

        //方法一、利用「元素長度」取得一維陣列內容值。
        for (int i = 0; i < arrStringA.Length; i++)
        {
            //輸出結果。
            Response.Write("方法一:" + arrStringA[i] + "
"); } //方法二、利用「特定維度」取得一維陣列內容值。從0開始算,表示一維度 for (int i = 0; i < arrStringA.GetLength(0); i++) { //輸出結果。 Response.Write("方法二:" + arrStringA[i] + "
"); } //方法三、利用「維度的上下限」取得一維陣列內容值。 for (int i = arrStringB.GetLowerBound(0); i < arrStringB.GetUpperBound(0) + 1; i++) { //輸出結果。 Response.Write("方法三:" + arrStringB[i] + "
"); } //方法四、利用「元素個數」取得一維陣列內容值。 for (int j = 0; j < (int)arrltStringC.Count; j++) { //輸出結果。 Response.Write("方法四:" + arrltStringC[j] + "
"); } //方法五、利用「集合迴圈」取得一維陣列內容值。 foreach (int intItem in arrIntA) { //輸出結果。 Response.Write("方法五:" + intItem.ToString() + "
"); } //方法六、利用「二層迴圈」取得二維陣列內容值。(Length=個數,Rank=維度) for (int x = 0; x < arrStringD.Rank; x++) { for (int y = 0; y < (arrStringD.Length / arrStringD.Rank); y++) { //輸出結果。 Response.Write("方法六:" + arrStringD[x, y] + "
"); } } //方法七、利用「集合迴圈」取得二維陣列內容值。 foreach (string strItem in arrStringD) { //輸出結果。 Response.Write("方法七:" + strItem + "
"); } //方法八、將字串內容依照特定符號所分割成為一維陣列元素讀取。 foreach (string strItem in arrStringE) { //當陣列元素項目不是空值時。 if (strItem.Trim() != "") { //輸出結果。 Response.Write("方法八:" + strItem + "
"); } } } }
轉載自 http://www.dotblogs.com.tw/wesley0917/archive/2010/12/21/20293.aspx

2011年12月5日 星期一

C# Sys.WebForms.PageRequestManagerServerErrorException(status code 500 OR 12031)問題

訊息: Sys.WebForms.PageRequestManagerServerErrorException: 處理伺服器上的要求時發生未知的錯誤。從伺服器傳回的狀態碼為: 12031
行: 4723
字元: 21
程式碼: 0
URI: http://emp.dhf.org.tw/ScriptResource.axd?d=4RQWgxT_AgXvyMs4acwyKSgCLJ6f9g019rfzWrKv9ltcx1RMW1Nv0ddpPltqc3UgqLqtkURdBv1V23tl4VW9SxCB_WLRaG-k68fmnBjWf4Uxu6UIeVk6FHwZ_hRrwmedi6pCD4iumBfCitXUm5mm8UDwJO_yKFKL-batYzrgScZg9fEA0&t=ffffffffd3a39141

在 </form> 標籤底下加入

2011年7月12日 星期二

C# 抓取資料夾檔案資訊存放在DataTable,並將檔案複製到其他位置

抓取資料夾檔案資訊存放在DataTable
        DataTable DT = new DataTable();
DT.Columns.Add("FullName");

foreach (string fname in System.IO.Directory.GetFileSystemEntries("D:\\WWW"))
{
if (fname.IndexOf(".doc") > 0 || fname.IndexOf(".docx") > 0)
{
DT.Rows.Add(fname);
}
}

GridView1.DataSource = DT;
GridView1.DataBind();

抓取資料夾完整檔案資訊存放在DataTable
        DataTable DT = new DataTable();
DT.Columns.Add("Sno");
DT.Columns.Add("Name");
DT.Columns.Add("FullName");
DT.Columns.Add("Extension");
DT.Columns.Add("Length");
DT.Columns.Add("Attributes");
DT.Columns.Add("CreationTime");
DT.Columns.Add("LastAccessTime");
DT.Columns.Add("LastWriteTime");
DT.Columns.Add("Directory");

int Sno = 1;
foreach (string FilePathName in System.IO.Directory.GetFileSystemEntries("D:\\WWW", "*.doc"))
{
//FileInfo 請 using System.IO;
FileInfo theFile;
theFile = new FileInfo(FilePathName);

if (theFile.Exists)
{
DT.Rows.Add(Sno, theFile.Name, theFile.FullName, theFile.Extension, theFile.Length, theFile.Attributes.ToString(), theFile.CreationTime, theFile.LastAccessTime, theFile.LastWriteTime, theFile.Directory);
Sno = Sno + 1;
}
}

GridView2.DataSource = DT;
GridView2.DataBind();

抓取資料夾MP3檔案資訊,並透過WindowsMediaPlayer抓取檔案資訊,存放在DataTable
        if (FileUpload1.PostedFile.ContentLength > 0)
{
DataTable DT = new DataTable();
DT.Columns.Add("Sno");
DT.Columns.Add("Name");
DT.Columns.Add("FullName");
DT.Columns.Add("Extension");
DT.Columns.Add("Directory");
DT.Columns.Add("Length");
DT.Columns.Add("出版商");
DT.Columns.Add("演唱者");
DT.Columns.Add("歌曲名稱");


foreach (string FilePathName in System.IO.Directory.GetFileSystemEntries(FileUpload1.PostedFile.FileName.Replace(FileUpload1.FileName, "")))
{
if (FilePathName.IndexOf(".mp3") > 0 || FilePathName.IndexOf(".wma") > 0)
{
//FileInfo 請 using System.IO;
FileInfo theFile;
theFile = new FileInfo(FilePathName);

if (theFile.Exists)
{
WMPLib.WindowsMediaPlayer wmp = new WMPLib.WindowsMediaPlayer();
wmp.settings.mute = true;
wmp.URL = theFile.FullName;
wmp.controls.play();
System.Threading.Thread.Sleep(100);

DT.Rows.Add(theFile.Name.Substring(0, 2), theFile.Name, theFile.FullName, theFile.Extension, theFile.Directory, theFile.Length, wmp.currentMedia.getItemInfo("Author"), wmp.currentMedia.getItemInfo("Artist"), wmp.currentMedia.getItemInfo("Title"));

wmp.close();
}
}
}

GridView2.DataSource = DT;
GridView2.DataBind();
}

將抓取到的資料檔案,複製檔案到其他位置(路徑)
        for (int i = 0; i < GridView2.Rows.Count; i++)
{
//原始檔案資料夾
String SourcePath = GridView2.Rows[i].Cells[9].Text + "\\" + GridView2.Rows[i].Cells[1].Text;
//要移至的檔案資料夾
String MoveToPath = "D:\\WWW\\" + GridView2.Rows[i].Cells[1].Text;

if (File.Exists(SourcePath))
{
File.Copy(SourcePath, MoveToPath, true);
}
}

        for (int i = 0; i < GridView2.Rows.Count; i++)
{
//原始檔案資料夾
String SourcePath = GridView2.Rows[i].Cells[9].Text + "\\" + GridView2.Rows[i].Cells[1].Text;
//要移至的檔案資料夾
String MoveToPath = "/RaWMroot/" + GridView2.Rows[i].Cells[1].Text;

if (File.Exists(SourcePath))
{
File.Copy(SourcePath, Server.MapPath(MoveToPath), true);
}
}

抓取上傳檔案完整路徑及名稱
Label1.Text = FileUpload1.PostedFile.FileName;

抓取上傳檔案路徑
Label1.Text = FileUpload1.PostedFile.FileName.Replace(FileUpload1.FileName, "");

參考網址 http://program.maomo.info/article.aspx?uid=64

2011年6月15日 星期三

C# 如何去除或有條件保留 HTML 標籤

/// 
/// 去除 HTML 標籤,可自訂合法標籤加以保留
///

/// 來源字串
/// 合法標籤集
///
public static string StripTags(string src, string[] reservedTagPool)
{
return Regex.Replace(
src,
String.Format("<(?!{0}).*?>", string.Join("|", reservedTagPool)),
String.Empty);
}


using System;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string html = "<div><p>OOXXOOXXOOXXOOXXOOXXOOXX!" + "<img src=\"http://www.OX.com.tw/Images/LoGO.gif\" alt=\"Logo\" /></p></div>";
string[] reservedTagPool = { "img", "br" };

TextBox1.Text = html;
TextBox2.Text = HtmlRemoval.StripTags(html, reservedTagPool);
Literal1.Text = HtmlRemoval.StripTags(html, reservedTagPool);
}
}
轉自 http://www.dotblogs.com.tw/hunterpo/archive/2010/11/26/19732.aspx

2011年6月11日 星期六

JavaScript C# 將網頁中的TextBox資料複製到剪貼簿中

在網頁中有 TextBox 與 Button 控制項,假如使用者在 TextBox 輸入完成後,按下Button,並不是把值帶到任何別的網頁或資料庫,只是把 TextBox 的值複製到 系統剪貼簿clipboard中,之後可以在任何網址列或文字文件把值在度貼上。

可以使用 JavaScript 的 window.clipboardData.setData 達成

C# 語法
this.Button1.Attributes.Add("onclick", @"javascript:window.clipboardData.setData('Text',document.getElementById('" + this.TextBox1.UniqueID + @"').value);");
VB.NET 語法
Me.Button1.Attributes.Add("onclick", "javascript:window.clipboardData.setData('Text',document.getElementById('" & Me.TextBox1.UniqueID & "').value);")

C# TextBox的文字排序和亂數排序

想要把C#裡的TextBox排序 其實原理來說並不難,除了TextBox.Text可以設定文字的屬性外 還有一個TextBox.Lines,代表的是TextBox中文字的行數(以"行"為分組的陣列) 型態為string[],所以也可以用這個Lines屬性設定文字的內容,然後針對string[]陣列 就可以直接用Array.Sort()這個方法來進行排序,看似很簡單 但是不知道是.net的bug還是怎樣 如果程式直接寫成這樣,Array.Sort(textBox1.Lines);textBox1是不會有反應的 還是呈現未排序前的狀態

所以要另外先把textBox1的內容存到一個暫存的陣列中 排序完再assign回去,為了簡化程式碼 因此把這功能寫成一個函式,此函式會把所接收到的textbox內容進行排序 (照字母順序排序)
private void sortTextBoxText(TextBox targetTextBox)
{
string[] temp = targetTextBox.Lines;
Array.Sort(temp);
targetTextBox.Lines = temp;
}

另外 如果要亂數排序的話也是一樣道理 可以透過Array.Sort(keys,items)這個方法,先亂數產生一個random index的陣列當keys 那Array.Sort()就會用這亂數keys排序後面的items,那我們的textbox就會變成亂數排序囉!
private void randomSortTextBoxText(TextBox targetTextBox)
{
string[] temp = targetTextBox.Lines;
double[] randomIndex = new double[temp.Length];
Random r = new Random();
for (int i = 0; i < temp.Length; i++)
{
randomIndex[i] = r.NextDouble();
}
Array.Sort(randomIndex,temp);
targetTextBox.Lines = temp;
}

2011年4月8日 星期五

在iframe中,如何讓 ASP.NET 使用 Session 資料時不要再自動消失

我們在 ASP.NET 網站使用 Session 時,常常因為 web.config 修改或更新 Bin\ 目錄下的 dll 而導致 Session 消失,Session 常常消失也挺惱人的,不是導致突然被自動登出,就是發生非預期的 Exception ... 等。 ( 有時候因為主機安裝防毒軟體也會造成 Session 資料無故消失,因為這些防毒軟體可能會誤判某檔案、某記憶體含有病毒資訊 )

這個時候我們可以將 Session 預設的模式 ( InProc ) 改成 StateServer 模式,但此時必須確認本機的 ASP.NET 狀態服務 是啟動的狀態!

請到 控制台 > 系統管理工具 > "服務"
找到 "ASP.NET 狀態服務" 或 "ASP.NET State Service"
此服務預設是屬於「停用」的狀態,請先切換到「自動」再按下「套用」再直接按「啟動」按鈕即可。

接者你可以到你的 ASP.NET 網站設定 web.config 組態檔,設定如下:
<configuration>
<system.web>
<sessionState mode="StateServer"
stateConnectionString="tcpip=localhost:42424"
cookieless="false"
timeout="20"/>
</system.web>
</configuration>
在web.config裡的cookieless="false"改為:cookieless="true"
這樣就可以將 Session 的資料存到本機的 ASP.NET 狀態服務去了,也不會無故 Session 自動消失了。

2010年12月9日 星期四

資料庫交易寫法TransactionScope、SqlTransact

資料庫交易寫法TransactionScope、SqlTransact
資料庫沒有了交易是很要命的,無法確保資料庫的正確,此篇就是在介紹交易的寫法。
string strConn = "連線字串"; 
SqlConnection conn = new SqlConnection(strConn);
conn.Open();
SqlTransaction tran = con.BeginTrasaction();
try
{
SqlCommand cmd = new SqlCommand("SQL語法", conn);
cmd.Transaction = tran;
//做你想做的...
//做完以後
tran.Commit();
}
catch
{
tran.Rollback();//發生例外就會滾回去
}
finally
{
conn.Dispose();
}


  using (TransactionScope scope = new TransactionScope()) 
{
string strConn = "連線字串";
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand("SQL語法", conn);
try
{
conn.Open();
//做你想做的...
//做完以後
scope.Complete();
}
//Mission Accomplished!
catch (Exception ex)
{
}
//發生例外時,會自動rollback

finally
{
cmd.Dispose();
conn.Close();
conn.Dispose();
}
}

搬移大量資料至 SQL Server

ADO.NET 的SqlBulkCopy 類別,用來搬移大量資料蠻好用的,雖然不是什麼新玩意兒,最近有一些需要,因此拿來用,記錄一下:
SqlConnection sqlconn = new SqlConnection(connstring);
SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(sqlconn);
using (sqlBulkCopy){ //大量複製的目的資料
sqlBulkCopy.DestinationTableName = destTable; sqlBulkCopy.WriteToServer(dr); //大量複製開始}
sqlconn.Close();

其中的destTable為 SQL Server 目的資料表,dr 則是來源資料,可以是DataReader或是 DataTable等等,來源資料不需要的是 SQL Server,只要能轉成DataReader或是 DataTable即可。

C# 使用SqlBulkCopy將資料批次寫入資料庫

之前demo有介紹利用SqlDataSoure和手動撰寫ADO.NET的方式大量新增資料的方法,雖然已經有效的改善了寫入的速度,但在發現了SqlBulkCopy以後,發現它更是威力強大,現在就來介紹SqlBulkCopy的猛。
  //一開始我們先產生一個DataTable來裝我們要寫入的資料 
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(int));
dt.Columns.Add("name", typeof(string));

//因為SqlBulkCopy的猛就是大量的一次寫入,所以我們也來跑10萬筆吧
int i;
for (i = 0; i < 100000; i++)
{
DataRow dr = dt.NewRow();
dr["name"] = i.ToString();
dt.Rows.Add(dr);
}

//宣告連結字串
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ASPNETDBConnectionString1"].ConnectionString);

conn.Open();
//宣告SqlBulkCopy
using (SqlBulkCopy sqlBC = new SqlBulkCopy(conn))
{
//設定一個批次量寫入多少筆資料
sqlBC.BatchSize = 1000;
//設定逾時的秒數
sqlBC.BulkCopyTimeout = 60;

//設定 NotifyAfter 屬性,以便在每複製 10000 個資料列至資料表後,呼叫事件處理常式。
sqlBC.NotifyAfter = 10000;
sqlBC.SqlRowsCopied += new SqlRowsCopiedEventHandler(OnSqlRowsCopied);

//設定要寫入的資料庫
sqlBC.DestinationTableName = "dbo.Table1";

//對應資料行
sqlBC.ColumnMappings.Add("id", "id");
sqlBC.ColumnMappings.Add("name", "name");

//開始寫入
sqlBC.WriteToServer(dt);
}
conn.Dispose();
}
void OnSqlRowsCopied(object sender, SqlRowsCopiedEventArgs e)
{
Response.Write("---
");
}

測試環境:SQL2005 Express
測試資料量:10萬筆
測試次數:10次
平均秒數:2.3532秒

太可怕啦,之前的寫法如果真的要寫10萬筆這種大量的資料都需花費一分鐘左右,但使用了SqlBulkCopy卻只要短短的兩秒鐘,下表看的出來如果資料筆數很少就沒必要使用SqlBulkCopy了。

寫入十萬筆資料10次的平均秒數
使用SqlBulkCopy:2.2051
使用AddWithValue:63.418
寫入一萬筆資料10次的平均秒數
使用SqlBulkCopy:0.2188
使用AddWithValue:6.3856
寫入一千筆資料10次的平均秒數
使用SqlBulkCopy:0.0187
使用AddWithValue:0.5805
寫入一百筆資料10次的平均秒數
使用SqlBulkCopy:0.0062
使用AddWithValue:0.0353
寫入十筆資料10次的平均秒數
使用SqlBulkCopy:0.004
使用AddWithValue:0.004

C# 將資料大量寫入資料庫時的優化寫法

當初學者需要利用for迴圈寫入資料時,常常會犯一個錯誤,就是SqlConnection開開關關,迴圈跑100次它就活生生開關一百次,雖然資料量小時看不出影響但這是相當浪費效能與資源的寫法,只要改變寫作習慣就可以避免掉這問題,來看看吧。

demo以GridView1秀出資料後再把它全部寫入到一個名為Table1的資料表。

以下是一般初學者會寫的code
for (int i = 0; i < this.GridView1.Rows.Count; i++) 
{
SqlConnection conn = demotools.getSqlConnection();//此為demo取得SqlConnection的方法
SqlCommand comm = new SqlCommand("INSERT INTO [Table1] ([name]) VALUES (@name)", conn);
conn.Open();
comm.Parameters.AddWithValue("name", this.GridView1.Rows[i].Cells[1].Text);
comm.ExecuteNonQuery();
conn.Dispose();
comm.Dispose();
}

沒錯這樣寫是可以正常的寫入資料庫,但是因為開關連結的方式包含在for迴圈內所以就會發生前文所說得問題,瘋狂的開關,為了節省效能我們應該這樣寫
SqlConnection conn = demotools.getSqlConnection(); 
SqlCommand comm = new SqlCommand("INSERT INTO [Table1] ([name]) VALUES (@name)", conn);
//以上都應該放在for迴圈外(除非你會變動=.=)

int i;
//宣告變數也應該放在外面不應該在for內

conn.Open();//開啟連結拿出來了

for (i = 0; i < this.GridView1.Rows.Count; i++)
{
comm.Parameters.Clear();//清除掉目前宣告出來的Parameters
comm.Parameters.AddWithValue("name", this.GridView1.Rows[i].Cells[1].Text);
comm.ExecuteNonQuery();
}
conn.Dispose();
comm.Dispose();


測試環境:SQL2005 Express
測試資料量:10萬筆
測試次數:10次
平均秒數:64.4867秒

這樣子的寫法是demo目前會的最好的寫法,當然我還很嫩其他的大大一定有更好的寫法還請多指教...當然其中還可以加上交易等判斷但那些不是此篇的重點所以demo以最簡單的方式寫出來,希望此篇對您會有所幫助,或許你懷疑SQL怎麼會那麼慢,請注意測試環境使用的是Express版本,並且10萬筆這種大筆數本來就不太應該用這方法寫...

C# 將資料大量寫入資料庫(使用SqlDataSoure)

上一篇介紹『將資料大量寫入資料庫時的優化寫法』是利用ADO.NET的寫法,但有些開發者習慣或是愛用等因素就是要用SqlDataSoure來完成,所以就出現了此篇文章啦

此篇只列出最重要的部份,您應該看了就懂了,至於頁面上的配置和該在什麼事件處理因人而異,demo就不多介紹了。

此篇的SqlDataSource名稱為SqlDataSource2
this.SqlDataSource2.InsertCommand = "INSERT INTO [Table1] ([name]) VALUES (@name)";//將Inster的SQL語句寫好 
this.SqlDataSource2.InsertParameters.Add("name", TypeCode.String, "");//宣告參數
int i;
for (i = 1; i <= 100; i++)
{
SqlDataSource2.InsertParameters["name"].DefaultValue = string.Format("第{0}筆", i);
SqlDataSource2.Insert();
}

2010年9月1日 星期三

C# 動態新增User Control,並設定屬性值與取屬性值

新增一個UserControl
ascx:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="CustIDName.ascx.cs" Inherits="UserControl_CustIDName" %>
<%@ Register Assembly="Joey" Namespace="Joey" TagPrefix="cc1" %>



.ascx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class UserControl_CustIDName : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{

}

public string CustID
{
get
{ return this.JoeyTextBox1.mTextBox.Text; }
set
{ this.JoeyTextBox1.mTextBox.Text = value; }

}
public string CustName
{
get
{ return this.JoeyTextBox2.mTextBox.Text; }
set
{ this.JoeyTextBox2.mTextBox.Text = value; }

}
public string ValidationGroup
{
get
{ return this.JoeyTextBox1.ValidationGroup; }
set
{
this.JoeyTextBox1.ValidationGroup = value;
this.JoeyTextBox2.ValidationGroup = value;
}
}
}

接著我們在一個空白頁面上,加入一個panel
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class LoopAddUserControl : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.DropDownList1.Items.Add(new ListItem("user control index"));
for (int i = 0; i < 10; i++)
{
this.DropDownList1.Items.Add(new ListItem(i.ToString()));
}
}

for (int index = 0; index < 10; index++)
{
Control ctlNewTrial = this.Page.LoadControl("UserControl/CustIDName.ascx");
SetUserControlProperty(ctlNewTrial, "ID", "Usrctrl" + index.ToString());
SetUserControlProperty(ctlNewTrial, "CustID", index.ToString());
SetUserControlProperty(ctlNewTrial, "CustName", index.ToString()+":name");

this.Panel1.Controls.Add(ctlNewTrial);
Label br = new Label();
br.Text = "index=" + index.ToString()+ "
";
this.Panel1.Controls.Add(ctlNewTrial);
this.Panel1.Controls.Add(br);
}
}

///
/// 設定user control的屬性值
///

/// usercontrol by page.loadcontrol()
/// usercontrol's property
/// setting property value
///
public void SetUserControlProperty(Control vobjControl, string vstrPropertyName, object vobjValue)
{
vobjControl.GetType().GetProperty(vstrPropertyName).SetValue(vobjControl, vobjValue, null);
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
ASP.usercontrol_custidname_ascx usrctl1 = (ASP.usercontrol_custidname_ascx)this.Panel1.FindControl("Usrctrl" + this.DropDownList1.SelectedValue);
if (usrctl1 != null)
{
this.TextBox1.Text = usrctl1.CustID;
this.TextBox2.Text = usrctl1.CustName;
}
else
{
this.TextBox1.Text = string.Empty;
this.TextBox2.Text = string.Empty;
}
}
}

參考文件
[ASP.NET]動態Load UserControl – part 2 - In 91- 點部落
WebUserControl之間值得傳遞(使用Interface) - topcat 姍舞之間的極度凝聚- 點部落
[ASP.NET]動態新增User Control,並設定屬性值與取屬性值 - In 91- 點部落

2010年8月24日 星期二

C# 動態載入MATA資訊

        HtmlMeta mata = new HtmlMeta();
mata.Attributes.Add("http-equiv", "X-UA-Compatible");
mata.Content = "IE=EmulateIE7";
this.Page.Header.Controls.Add(mata);

2010年8月11日 星期三

C# ListView 之 NumericPagerField 類別 設定分頁分法

CSS 頁碼屬性
CurrentPageLabelCssClass 目前頁碼的 CSS 類別。
NextPreviousButtonCssClass 下一頁和上一頁按鈕的 CSS 類別。
NumericButtonCssClass 表示頁碼之按鈕的 CSS 類別

參考 http://msdn.microsoft.com/zh-tw/library/system.web.ui.webcontrols.numericpagerfield(VS.90).aspx

C# 如何從字符串中刪除 HTML標籤

using System.Text.RegularExpressions;
Regex.Replace(字串,@"<(.| \ ñ )*?>", string.Empty)

C# Left、Right' Mid 都可以用

        public string  StrLeft(string s, int length)
{
return s.Substring(0, length);
}

public string StrRigth(string s, int length)
{
return s.Substring(s.Length - length);
}

public string StrMid(string s, int start, int length)
{
return s.Substring(start, length);
}

str = "123456789"
Left = str.substring(0,2) = "12"
Rigth = str.substring(str.length -2) = "89"
Mid = strsubstring(2,2) = "34"

using Microsoft.VisualBasic;
Strings.Right("aaaaa",2);

2010年7月27日 星期二

C# 如何在ASP.NET 寫入檔案(上傳檔案)到虛擬目錄中

web.config 設定要存取虛擬目錄(網路芳鄰的電腦資料夾)存取帳號密碼
<configuration>
<configSections>
.......................略過
</configSections>
<system.web>
<identity impersonate="true" userName="AAAA" password="0000" />
</system.web>
<connectionStrings>

上傳檔案的方式 C# ASP.NET 語法
FileUpload tempUpload = FileUpload1;
tempUpload.PostedFile.SaveAs(Server.MapPath(VirtualPathUtility.ToAbsolute(Server.UrlDecode("~/虛擬目錄別名/"))) + ServerFileName);

FileUpload tempUpload = FileUpload1;
tempUpload.PostedFile.SaveAs("\\\\192.168.0.10\\資料夾\\" + ServerFileName);

2010年7月20日 星期二

C# VB 確認字串是否為有效的電子郵件格式

C# 寫法
using System;
using System.Text.RegularExpressions;

public class RegexUtilities
{
public static bool IsValidEmail(string strIn)
{
// Return true if strIn is in valid e-mail format.
return Regex.IsMatch(strIn,
@"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))" +
@"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$");
}
}

VB寫法
Imports System.Text.RegularExpressions

Module RegexUtilities
Function IsValidEmail(ByVal strIn As String) As Boolean
' Return true if strIn is in valid e-mail format.
Return Regex.IsMatch(strIn, _
"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))" + _
"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$")
End Function
End Module

這個範例可以解譯規則運算式模式 ^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$,其方式如下表所示

^
在字串開頭開始比對。

(?("")
判斷第一個字元是否為引號。(?("") 是交替建構的開頭。

((?("")("".+?""@)
如果第一個字元是引號,則比對開頭引號,其後接著至少一個任何字元的項目,再加上結尾引號。字串應該以 @ 符號為結束。

|(([0-9a-zA-Z]
如果第一個字元不是引號,則比對由 a 到 z 的任何字母字元,或由 0 到 9 的任何數值字元。

(\.(?!\.))
如果下一個字元是句號,就找到相符的比對。如果不是句號,則往前找下一個字元並繼續進行比對。(?!\.) 是零寬度右不合樣 (Negative Lookahead) 判斷提示,可以避免兩個連續句號在電子郵件地址的本機部分中出現。

|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w]
如果下一個字元不是句號,則比對任何字組字元或下列其中一個字元:-!#$%'*+=?^`{}|~。

((\.(?!\.))|[-!#\$%'\*\+/=\?\^`\{\}\|~\w])*
比對零次或更多次交替模式 (句號後接非句號或幾個字元的其中一個字元)。

@
比對 @ 字元。

(?<=[0-9a-zA-Z])
如果 @ 字元前面的字元是由 A 到 Z、a 到 z 或 0 到 9 的字元,則繼續比對。(?<=[0-9a-zA-Z]) 建構定義零寬度左合樣 (Positive Lookbehind) 判斷提示。

(?(\[)
檢查 @ 後面的字元是否為左方括號。

(\[(\d{1,3}\.){3}\d{1,3}\])
如果是左方括號,則比對後面接著 IP 位址 (四組一至三位的數字,各組間以句號分隔) 及右方括號的左方括號。

|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6})
如果 @ 後面跟著的字元不是左方括號,則比對一個值為 A-Z、a-z 或 0-9 的英數字元,其後接著零個或更多字組字元或連字號的項目,再加上一個值為 A-Z、a-z 或 0-9 的英數字元,然後再接句號。這個模式可能重複一次或多次,然後接著兩個到六個英文字母 (a-z、A-Z) 字元。規則運算式中這個部分的設計是要用來擷取網域名稱。

參考資料 http://msdn.microsoft.com/zh-tw/library/01escwtf(VS.95).aspx

2010年6月20日 星期日

GridView如何抓取已經隱藏的欄位值

有很多時候一些欄位不想給使用者看到,但是卻必須利用那些欄位的值作一些判斷,試過了Row.Cells和FindControl都找不到它該怎麼辦勒...以下介紹兩種方式來讓您找到隱藏的欄位值。

此篇由demo分享,因我同事之前也有遇到相同問題,故記錄下來

第一種方式算是比較小技巧的我們再GridView的RowCreated事件中撰寫以下code
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)     
{
if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header)
e.Row.Cells[0].Visible = false;
}

然後在RowDataBound事件中,一樣可以利用Row.Cells的方式找到它
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)     
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string aa = e.Row.Cells[0].Text;
}
}

第二種方式看起來就比較有點水準@@
我們是直接使用ui介面把某個欄位隱藏起來(Visible = False),然後直接指定DataItem的方式去找到它,我們需要在RowDataBound事件撰寫以下code
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)     
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Boolean draft = Convert.ToBoolean(DataBinder.Eval(e.Row.DataItem, "draft"));
if (draft == true)
e.Row.ForeColor = System.Drawing.Color.Green;
}
}

以上的code我是把draftx欄位轉換成布林,然後去判斷是真是假再去對該ROW的字色作變換
轉載自 http://demo.tc/Post/88