2013年6月27日 星期四

ASP.NET Copy File to Network Share Folder 複製檔案到網路磁碟機

ASP.NET Copy File to Network Share Folder
複製檔案到網路磁碟機


C#:
  1. private void CopyFileToNetwork()
  2. {
  3. System.IO.StreamReader sErr;
  4. System.IO.StreamReader sOut;
  5. String tempErr, tempOut;
  6. System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
  7. myProcess.StartInfo.FileName = @"NET";
  8. myProcess.StartInfo.Arguments = "USE Y: \\\\192.168.0.136\\folder001 \"123456\" /user:\"Administrator\""; //password is 123456, username is Administrator
  9. myProcess.StartInfo.CreateNoWindow = true;
  10. myProcess.StartInfo.UseShellExecute = false;
  11. myProcess.StartInfo.RedirectStandardError = true;
  12. myProcess.StartInfo.RedirectStandardOutput = true; // 導出 StandardOutput
  13. try
  14. {
  15. myProcess.Start();
  16. myProcess.WaitForExit(10000);
  17.  
  18. if (!myProcess.HasExited)
  19. {
  20. myProcess.Kill();
  21. Response.Write("執行失敗!!");
  22. }
  23. else
  24. {
  25. sErr = myProcess.StandardError;
  26. tempErr = sErr.ReadToEnd();
  27. sErr.Close();
  28.  
  29. sOut = myProcess.StandardOutput;
  30. tempOut = sOut.ReadToEnd();
  31. sOut.Close();
  32.  
  33. if (myProcess.ExitCode == 0) //連線磁碟機建立成功
  34. {
  35. //Response.Write("執行成功" + "<BR>" + tempOut.ToString()); // 把執行結果也印出來
  36. System.IO.File.Copy(@"D:\abc.xls", @"Y:\abc.xls",true);
  37. }
  38. else if (myProcess.ExitCode == 2) // 忽略連線磁碟機已存在
  39. {
  40. System.IO.File.Copy(@"D:\abc.xls", @"Y:\abc.xls", true);
  41. }
  42. else
  43. {
  44. Response.Write(tempErr);
  45. }
  46. }
  47. }
  48. catch (Exception ex)
  49. {
  50. Response.Write(ex.Message);
  51. myProcess.Close();
  52. }
  53. finally
  54. {
  55. myProcess.Close();
  56. }
  57. }

2013年6月17日 星期一

ASP.NET Request.UrlReferrer取得上一頁的網址

ASP.NET Request.UrlReferrer取得上一頁的網址


HTML:
  1. <form id="form1" runat="server">
  2. <div>
  3. <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
  4. <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
  5. </div>
  6. </form>

C#:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7.  
  8. public partial class Test_tsUrlReferrer : System.Web.UI.Page
  9. {
  10. protected void Page_Load(object sender, EventArgs e)
  11. {
  12. try
  13. {
  14. ViewState["UrlReferrer"] = "";
  15. if (!IsPostBack)
  16. {
  17. if (Request.UrlReferrer != null)
  18. ViewState["UrlReferrer"] = Request.UrlReferrer.ToString();
  19. }
  20. Label1.Text = ViewState["UrlReferrer"].ToString();
  21. }
  22. catch (Exception ex)
  23. {
  24. throw ex;
  25. }
  26. }
  27. protected void Button1_Click(object sender, EventArgs e)
  28. {
  29. try
  30. {
  31. Response.Redirect(ViewState["UrlReferrer"].ToString());
  32. }
  33. catch (Exception)
  34. {
  35. throw;
  36. }
  37. }
  38. }

2013年6月12日 星期三

X-UA-Compatible設置IE兼容模式

[HTML]X-UA-Compatible設置IE兼容模式

強制瀏覽器呈現為特定的版本的標準。它不支持IE7及以下:
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7"/>

如果用分號分開,它設置為不同版本的兼容級別,IE7、IE9。它允許不同層次的向後兼容性:
<meta http-equiv="X-UA-Compatible" content="IE=7; IE-9"/>

只選擇其中一個選項:
<meta http-equiv="X-UA-Compatible" content="IE=9">
<meta http-equiv="X-UA-Compatible" content="IE=8"/>
<meta http-equiv="X-UA-Compatible" content="IE=7">
<meta http-equiv="X-UA-Compatible" content="IE=5">

允許更容易的測試和維護。雖然通常比較有用的版本,這是使用模擬:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9"/>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8"/>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7">

什麼版本IE 就用什麼版本的標準模式:
<meta http-equiv="X-UA-Compatible" content="IE=edge">

使用以下代碼強制IE 使用Chrome Frame:
<meta http-equiv="X-UA-Compatible" content="chrome=1">

最佳的兼容模式方案,結合考慮以上兩種:
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

指定文件兼容性模式,在網頁中使用meta元素放入X-UA-Compatible  http-equiv  標頭。以下是指定為Emulate IE7 mode兼容性之範例:
< html >
< head >
  <!--  Mimic Internet Explorer 7  -->
  < meta  http-equiv ="X-UA-Compatible"  content ="IE=EmulateIE7"  />
  < title > My Web Page </ title >
< / head >
< body >
</ body >
</ html >

設定網站服務器以指定預設兼容性模式:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
   <system.webServer>
      <httpProtocol>
         <customHeaders>
            <clear />
            <add name="X-UA-Compatible" value="IE=EmulateIE7" />
         </customHeaders>
      </httpProtocol>
   </system.webServer>
</configuration>

2013年6月11日 星期二

ASP.NET 使用JavaScript

ASP.NET 使用JavaScript


C#:
  1. string strScript = "alert(\"建立完成!\");";
  2. ScriptManager.RegisterStartupScript(this, typeof(string), "ALERT", strScript, true);
  3.  
  4. string strScript = "<script>alert(\"建立完成!\");</script>";
  5. this.Page.Controls.Add(new LiteralControl(str_Script));

ASP.NET 新增資料後立即取得自動編號的ID(2)

ASP.NET 新增資料後立即取得自動編號的ID(2)


HTML:
  1. <asp:SqlDataSource ID="SqlDataSource1" runat="server"
  2. ConnectionString="<%$ ConnectionStrings:KMSConnectionString %>"
  3. InsertCommand="INSERT INTO category(cat001, cat002, objactive, objcreate) VALUES (@cat001,@cat002,@objactive,@objcreate);select @ID=@@Identity
  4. " oninserted="SqlDataSource1_Inserted">
  5. <InsertParameters>
  6. <asp:ControlParameter Name="cat001" ControlID="cat001" Type="String" />
  7. <asp:Parameter Name="cat002" DefaultValue="Folder" Type="String" />
  8. <asp:ControlParameter Name="objactive" ControlID="objactive" Type="String" />
  9. <asp:Parameter Name="objcreate" Type="String" />
  10. <asp:Parameter Name="ID" Direction="InputOutput" Type="Decimal" />
  11. </InsertParameters>
  12. </asp:SqlDataSource>

C#:
  1. protected void SaveButton_Click(object sender, ImageClickEventArgs e)
  2. {
  3. SqlDataSource1.InsertParameters["objcreate"].DefaultValue = Context.User.Identity.Name;
  4. SqlDataSource1.Insert();
  5. }
  6. protected void SqlDataSource1_Inserted(object sender, SqlDataSourceStatusEventArgs e)
  7. {
  8. string strReturn = e.Command.Parameters["@ID"].Value.ToString();
  9. }

ASP.NET 新增資料後立即取得自動編號的ID(1)

ASP.NET 新增資料後立即取得自動編號的ID(1)


C#:
  1. SqlConnection conn = new SqlConnection(ConnectionString);
  2. conn.open();
  3. string strSQL = "Insert Into table1(t1,t2) value(1,2);select @@IDENTITY";
  4. SqlCommand cmd = new SqlCommand(strSQL);
  5. cmd.Connection = conn;
  6. int i = cmd.ExecuteScalar(); //i就是你要的
  7. cmd.Dispose();
  8. conn.close();
  9. conn.Dispose()

VB:
  1. Dim cid As String = ""
  2. Dim conn As SqlConnection
  3. conn = Class1.conn_sql
  4. Dim command As New SqlCommand("INSERT INTO [Categories] ([CategoryName], [Description]) VALUES (@CategoryName, @Description);SELECT SCOPE_IDENTITY() ;", conn)
  5. command.Parameters.AddWithValue("@CategoryName", "test")
  6. command.Parameters.AddWithValue("@Description", "abcd")
  7. conn.Open()
  8. cid = command.ExecuteScalar
  9. conn.Close()

ASP.NET 取得Windows驗証Login ID

ASP.NET 取得Windows驗証Login ID


C#:
  1. private string GetLogonUserID()
  2. {
  3. string strLogonUser = Request.LogonUserIdentity.Name.Substring(Request.LogonUserIdentity.Name.IndexOf("\\") + 1, Request.LogonUserIdentity.Name.Length - Request.LogonUserIdentity.Name.IndexOf("\\") - 1);
  4. return strLogonUser.ToString();
  5. }

SQL 列出資料庫中所有的Table

SQL 列出資料庫中所有的Table


MsSQL:
  1. SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE (TABLE_TYPE = 'BASE TABLE') AND (TABLE_SCHEMA = 'dbo')

Access:
  1. SELECT * FROM MSYSOBJECTS

Oracle:
  1. SELECT * FROM USER_OBJECTS

ASP.NET ListBox 互傳

ASP.NET ListBox 互傳


HTML:
  1. <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple">
  2. <asp:ListItem>a</asp:ListItem>
  3. <asp:ListItem>b</asp:ListItem>
  4. <asp:ListItem>c</asp:ListItem>
  5. </asp:ListBox>
  6. <asp:Button ID="Button1" runat="server" Text="Add" onclick="Button1_Click" />
  7.  
  8. <asp:ListBox ID="ListBox2" runat="server" SelectionMode="Multiple">
  9. </asp:ListBox>
  10. <asp:Button ID="Button2" runat="server" Text="Del" onclick="Button2_Click" />

C#:
  1. protected void Button1_Click(object sender, EventArgs e)
  2. {
  3. //單選add時用下列這行
  4. //ListBox2.Items.Add(ListBox1.SelectedItem);
  5.  
  6. //多選add用迴圈
  7. for (int i = 0; i < ListBox1.Items.Count; i++)
  8. {
  9. if (ListBox1.Items[i].Selected)
  10. {
  11. ListBox2.Items.Add(ListBox1.Items[i]);
  12. }
  13. }
  14. }
  15.  
  16. protected void Button2_Click(object sender, EventArgs e)
  17. {
  18. //單選del
  19. //ListBox2.Items.RemoveAt(ListBox2.SelectedIndex);
  20.  
  21. //多選del用迴圈
  22. for (int i = ListBox2.Items.Count - 1; i >= 0; i--)
  23. {
  24. if (ListBox2.Items[i].Selected)
  25. {
  26. ListBox2.Items.RemoveAt(i);
  27. }
  28. }
  29. }

2013年6月6日 星期四

ASP.NET DropDownList 尋找符合項目

ASP.NET DropDownList 尋找符合項目


C#:
  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3. //由於DropDownList只能單選,為了避免錯誤,先將已選定的項目取消
  4. this.DropDownList1.Items[DropDownList1.SelectedIndex].Selected = false;
  5.  
  6. //尋找符合"1"的項目
  7. ListItem item=this.DropDownList1.Items.FindByValue("1");
  8.  
  9. //如果在DropDownList清單中有找到相符的,則將它改成被選取的項目
  10. if(item!=null)item.Selected = true;
  11. }

2013年6月5日 星期三

C# ASCII字碼轉換應用

C# ASCII字碼轉換應用

如何將英文字母大寫”A”轉換為”65”與如何將”65”轉換為英文字母大寫的”A”。
下列範例中RetAsciiCode將大寫”A”轉換成”65”後return給呼叫RetAsciiCode的原程序變數,另外RetAsciiChar帶入一個數字(asciiCode)例如”65”,轉換成大寫”A”並將結果return給呼叫的原程序變數。

C#:
  1. int intAsciiCode = Int32.Parse(RetAsciiCode(“A”)); //回傳數字65
  2. string strAsciiChar = RetAsciiChar(65); //回傳大寫A
  3.  
  4. public int RetAsciiCode(string MyString)
  5. {
  6. if (MyString.Length == 0)
  7. return 0;
  8. else if (MyString.Length > 1)
  9. MyString = MyString[0].ToString();
  10.  
  11. int AsciiCodeO = (int)System.Convert.ToChar(MyString);
  12. byte[] AsciiCodeB = System.Text.Encoding.ASCII.GetBytes(MyString);
  13. //int AsciiCode = System.Convert.ToInt32(AsciiCodeB);
  14. return AsciiCodeO;
  15. }
  16.  
  17. public string RetAsciiChar(int AsciiCode)
  18. {
  19. return System.Convert.ToChar(AsciiCode).ToString();
  20. }

C# Get MAC Address

Get MAC Address C#

C#
  1. public string GetMACAddress()
  2. {
  3. ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
  4. ManagementObjectCollection moc = mc.GetInstances();
  5. string MACAddress = String.Empty;
  6. foreach (ManagementObject mo in moc)
  7. {
  8. if (MACAddress == String.Empty) // only return MAC Address from first card
  9. {
  10. if ((bool)mo["IPEnabled"] == true) MACAddress = mo["MacAddress"].ToString();
  11. }
  12. mo.Dispose();
  13. }
  14. return MACAddress;
  15. }

ASP.NET Encrypt Excel加密

ASP.NET Encrypt Excel加密

C#:
  1. private void EncryptExcel(string FileName)
  2. {
  3. try
  4. {
  5. FileName = @"D:\Inetpub\PORTAL\Test\MyFilests.xlsx";
  6.  
  7. Microsoft.Office.Interop.Excel.Application xlApp = null;
  8. Workbook wb = null;
  9. Worksheet ws = null;
  10. Range aRange = null;
  11. xlApp = new Microsoft.Office.Interop.Excel.Application();
  12.  
  13. //打開Server上的Excel檔案
  14. xlApp.Workbooks.Open(FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
  15. //第一個Workbook
  16. wb = xlApp.Workbooks[1];
  17. //設密碼
  18. wb.Password = "123456";
  19. //另存新檔
  20. wb.SaveAs(@"D:\Inetpub\PORTAL\Test\NewPasswordx.xlsx");
  21. //取得worksheet
  22. ws = (Worksheet)wb.Worksheets[1];
  23. Label1.Text = ws.Name;
  24. //開啟檔案
  25. System.Diagnostics.Process.Start(@"D:\Inetpub\PORTAL\Test\NewPasswordx.xlsx");
  26.  
  27. }
  28. catch (Exception)
  29. {
  30.  
  31. throw;
  32. }
  33. }

ASP.NET TextBox onKeyDown網頁中按Enter鍵後指定一個Button並送出

ASP.NET TextBox onKeyDown網頁中按Enter鍵後指定一個Button並送出

在TextBox1下按Enter之後,觸發Script Event onKeyDown,執行window.open到google網頁;另一個觸發.Net ImageButton1_Click,Redirect到www.msn.com.tw。以上觸發Event會跳過Button1


JavaScript:
  1. <script language="javascript" type='text/javascript'>
  2.  
  3. function body_onKeyDown() {
  4. if (window.event.keyCode == 13) {
  5. alert(event.type);
  6. document.all.ImageButton1.focus();
  7. newWindow = window.open("http://www.google.com", "SelectUser", "width=500,height=500");
  8. newWindow.focus();
  9. }
  10. }
  11. </script>

HTML:
  1. <body onkeydown="body_onKeyDown()">
  2. <form id="form1" runat="server">
  3. <div>
  4. <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
  5. <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
  6. <asp:ImageButton ID="ImageButton1" runat="server"
  7. onclick="ImageButton1_Click" />
  8. </div>
  9. </form>
  10. </body>

C#:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7.  
  8. public partial class Test_tsOnKeyDown : System.Web.UI.Page
  9. {
  10. protected void Page_Load(object sender, EventArgs e)
  11. {
  12.  
  13. }
  14. protected void Button1_Click(object sender, EventArgs e)
  15. {
  16. Response.Redirect("http://www.yahoo.com.tw");
  17. }
  18. protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
  19. {
  20. Response.Redirect("http://www.msn.com.tw");
  21. }
  22. }

ASP.NET Dynamic InnerHTML

ASP.NET Dynamic InnerHTML

HTML:
  1. <body>
  2. <form id="form1" runat="server">
  3. <div>
  4. <asp:Button ID="Button1" runat="server" Text="Inner" OnClick="Button1_Click" />
  5. </div>
  6. <div id="dynamic1">
  7. </div>
  8. <div id="dynamic2" runat="server">
  9. </div>
  10. </form>
  11. </body>

C#:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7.  
  8. public partial class Test_tsInnerHTML : System.Web.UI.Page
  9. {
  10. protected void Page_Load(object sender, EventArgs e)
  11. {
  12. }
  13. protected void Button1_Click(object sender, EventArgs e)
  14. {
  15. try
  16. {
  17. //Script
  18. string strScript = "document.getElementById('dynamic1').innerHTML='<input type=\"file\" name=\"FileUpload1\" id=\"FileUpload1\" />'";
  19. ScriptManager.RegisterStartupScript(this, typeof(string), "Function", strScript, true);
  20. //Asp.net
  21. dynamic2.InnerHtml = Server.HtmlDecode("<Input type='file' name='fileupload2' id='fileupload2'>");
  22. }
  23. catch (Exception)
  24. {
  25. throw;
  26. }
  27. }
  28. }

C# Excel to GridView

[C#]Excel to GridView

HTML:
  1. <form id="form1" runat="server">
  2. <div>
  3. <asp:FileUpload ID="FileUpload1" runat="server" />
  4. <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />
  5. <br />
  6. <asp:GridView ID="GridView1" runat="server">
  7. </asp:GridView>
  8. <asp:Label ID="lbl_Err" runat="server" Text="Label"></asp:Label><br />
  9. <div runat="server" clientidmode="Static" id="DIV1">
  10. </div>
  11. </div>
  12. </form>

C#:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. using System.Data;
  8.  
  9. public partial class Test_FileUpload : System.Web.UI.Page
  10. {
  11. protected void Page_Load(object sender, EventArgs e)
  12. {
  13. }
  14. protected void Button1_Click(object sender, EventArgs e)
  15. {
  16. try
  17. {
  18. string FileFullPath = string.Empty;
  19. DataSet ds = null;
  20. DataTable dt = null;
  21.  
  22. File_Upload flu = new File_Upload();
  23. flu.Set_AllowedExtension = "EXCEL";
  24. flu.UploadXLS(FileUpload1);
  25. ImportData imp = new ImportData();
  26. ds = imp.GetExcelData(flu.Get_SavePath + flu.Get_FileName);
  27. dt = ds.Tables[0];
  28. GridView1.DataSource = dt;
  29. GridView1.DataBind();
  30. }
  31. catch (Exception ex)
  32. {
  33. lbl_Err.Text = ex.Message;
  34. }
  35. }
  36. }

C# 網頁PostBack後回到原來停留的位置

[C#]網頁PostBack後回到原來停留的位置

web.config
  1. <?xml version="1.0"?>
  2.  
  3. <configuration>
  4.  
  5. <system.web>
  6.  
  7. <!--網頁PostBack後回到原來停留的位置-->
  8.  
  9. <pages maintainScrollPositionOnPostBack="true">
  10.  
  11. </pages>
  12.  
  13. </system.web>
  14.  
  15. </configuration>

2013年6月4日 星期二

C# ViewState存入Session

[C#]ViewState存入Session


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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

    }

    /// <summary>
    /// ViewState存在Session
    /// </summary>
    protected override PageStatePersister PageStatePersister
    {
        get
        {
            //return base.PageStatePersister;
            return new SessionPageStatePersister(this);
        }
     }
}

C# 呼叫外部檔案

[C#]呼叫外部檔案


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            System.Diagnostics.Process.Start(@"c:\GetApplicationBG.exe");

            #region Sample
            // open text file in notepad (or another default text editor)
            //System.Diagnostics.Process.Start(@"c:\textfile.txt");

            // open image in default viewer
            //System.Diagnostics.Process.Start(@"c:\image.jpg");

            // open url in default web browser
            //System.Diagnostics.Process.Start("http://www.csharp-examples.net");

            // open PDF file
            //System.Diagnostics.Process.Start(@"c:\document.pdf");

            #endregion
        }
        catch (Exception)
        {
         
            throw;
        }
    }
}

C# 日期相減

[C#]日期相減


  1. using System;
  2.  
  3. using System.Collections.Generic;
  4.  
  5. using System.Linq;
  6.  
  7. using System.Web;
  8.  
  9. using System.Web.UI;
  10.  
  11. using System.Web.UI.WebControls;
  12.  
  13.  
  14.  
  15. public partial class Test_tsDateSubtract : System.Web.UI.Page
  16.  
  17. {
  18.  
  19.     protected void Page_Load(object sender, EventArgs e)
  20.  
  21.     {
  22.  
  23.         DateTime StartTime = DateTime.Parse("2013-05-20"); //開始日
  24.  
  25.         //DateTime EndTime = DateTime.Parse("2013-05-21"); //指定結束日
  26.  
  27.         DateTime EndTime = DateTime.Now; //當日
  28.  
  29.         TimeSpan TS = EndTime.Subtract(StartTime); //日期相減
  30.  
  31.  
  32.  
  33.         Response.Write(TS.Days.ToString() + "<br>");         //天(int)
  34.  
  35.         Response.Write(TS.Hours.ToString() + "<br>");        //小時(int)
  36.  
  37.         Response.Write(TS.Minutes.ToString() + "<br>");      //分(int)
  38.  
  39.  
  40.  
  41.         Response.Write(TS.TotalDays.ToString() + "<br>");    //天(double)
  42.  
  43.         Response.Write(TS.TotalHours.ToString() + "<br>");   //小時(double)
  44.  
  45.         Response.Write(TS.TotalSeconds.ToString() + "<br>"); //分(double)
  46.  
  47.     }
  48.  
  49. }

C# 取得Browser Language

[C#]取得Browser Language


  1. using System;
  2.  
  3. using System.Collections.Generic;
  4.  
  5. using System.Linq;
  6.  
  7. using System.Web;
  8.  
  9. using System.Web.UI;
  10.  
  11. using System.Web.UI.WebControls;
  12.  
  13.  
  14.  
  15. public partial class Test_tsBrowserLanguage : System.Web.UI.Page
  16.  
  17. {
  18.  
  19.     protected void Page_Load(object sender, EventArgs e)
  20.  
  21.     {
  22.  
  23.         try
  24.  
  25.         {
  26.  
  27.             HttpRequest Request = HttpContext.Current.Request;
  28.  
  29.             string browerlang = Request.UserLanguages[0].ToString();
  30.  
  31.             Response.Write(browerlang);
  32.  
  33.         }
  34.  
  35.         catch (Exception ex)
  36.  
  37.         {
  38.  
  39.             throw ex;
  40.  
  41.         }
  42.  
  43.     }
  44.  
  45. }

C# DataTable to XML

[C#]DataTable to XML


  1. using System;
  2.  
  3. using System.Collections.Generic;
  4.  
  5. using System.Linq;
  6.  
  7. using System.Web;
  8.  
  9. using System.Web.UI;
  10.  
  11. using System.Web.UI.WebControls;
  12.  
  13. using System.Data.SqlClient;
  14.  
  15. using System.Data;
  16.  
  17. using System.Xml;
  18.  
  19. using System.Xml.Linq;
  20.  
  21. using System.Text;
  22.  
  23.  
  24.  
  25. public partial class Test_tsDataTabletoXML : System.Web.UI.Page
  26.  
  27. {
  28.  
  29.     protected void Page_Load(object sender, EventArgs e)
  30.  
  31.     {
  32.  
  33.         try
  34.  
  35.         {
  36.  
  37.             SqlConnection cn = new SqlConnection();
  38.  
  39.             cn.ConnectionString = "Data Source=localhost;Initial Catalog=db1;Persist Security Info=True;User ID=sa;Password=123456";
  40.  
  41.  
  42.  
  43.             SqlCommand cmd = new SqlCommand();
  44.  
  45.             cmd.Connection = cn;
  46.  
  47.             cmd.CommandText = "select * from Product";
  48.  
  49.  
  50.  
  51.             cn.Open();
  52.  
  53.             SqlDataAdapter da = new SqlDataAdapter();
  54.  
  55.             da.SelectCommand = cmd;
  56.  
  57.             DataSet ds = new DataSet("ds1");
  58.  
  59.             da.Fill(ds, "Product");
  60.  
  61.             DataTable dt = ds.Tables["Product"];
  62.  
  63.  
  64.  
  65.             // XML Setting
  66.  
  67.             XmlWriterSettings settings = new XmlWriterSettings();
  68.  
  69.             settings.Indent = false;
  70.  
  71.             settings.Encoding = settings.Encoding = Encoding.GetEncoding("utf-8");
  72.  
  73.  
  74.  
  75.             // XML Write
  76.  
  77.             XElement tElement = new XElement("DataTable", "");
  78.  
  79.             using (XmlWriter xmlWriter = XmlWriter.Create("c:\\Product.xml", settings))
  80.  
  81.             {
  82.  
  83.                 // Write the data set to the writer.
  84.  
  85.                 tElement = DataTableToXml(dt, "root");
  86.  
  87.                 tElement.WriteTo(xmlWriter);
  88.  
  89.             }
  90.  
  91.         }
  92.  
  93.         catch (Exception ex)
  94.  
  95.         {
  96.  
  97.             throw ex;
  98.  
  99.         }
  100.  
  101.     }
  102.  
  103.  
  104.  
  105.     /// <summary>
  106.  
  107.     /// DataTable to XML
  108.  
  109.     /// </summary>
  110.  
  111.     /// <param name="pAttributeTable"></param>
  112.  
  113.     /// <param name="tParentTag"></param>
  114.  
  115.     /// <returns></returns>
  116.  
  117.     private XElement DataTableToXml(DataTable pAttributeTable, string tParentTag)
  118.  
  119.     {
  120.  
  121.         if (pAttributeTable == null)
  122.  
  123.             return null;
  124.  
  125.  
  126.  
  127.         XElement tParent = null;
  128.  
  129.         try
  130.  
  131.         {
  132.  
  133.             tParent = new XElement(tParentTag);  // 集合Tag的名字
  134.  
  135.             //每個DataRow為屬性分類
  136.  
  137.             foreach (DataRow tRow in pAttributeTable.Rows)
  138.  
  139.             {
  140.  
  141.                 XElement tChild = new XElement("DataRow");
  142.  
  143.                 //每個DataRow的DataColumn為屬性分類裡的項目
  144.  
  145.                 foreach (DataColumn tColumn in pAttributeTable.Columns)
  146.  
  147.                 {
  148.  
  149.                     tChild.Add(new XElement(tColumn.ColumnName, tRow[tColumn]));
  150.  
  151.                 }
  152.  
  153.                 tParent.Add(tChild);
  154.  
  155.             }
  156.  
  157.         }
  158.  
  159.         catch (Exception ex)
  160.  
  161.         {
  162.  
  163.             throw ex;
  164.  
  165.         }
  166.  
  167.         return tParent;
  168.  
  169.     }
  170.  
  171. }

C# DataList取得ItemTemplate欄位值

[C#]DataList取得ItemTemplate欄位值

  1. <asp:DataList ID="DataList1" runat="server">
  2.  
  3.             <ItemTemplate>
  4.  
  5.                 <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
  6.  
  7.                 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
  8.  
  9.                 <asp:DropDownList ID="ddlLang" runat="server">
  10.  
  11.                     <asp:ListItem Text="en" Value="epaper_en.htm"></asp:ListItem>
  12.  
  13.                     <asp:ListItem Text="tw" Value="epaper_tw.htm"></asp:ListItem>
  14.  
  15.                     <asp:ListItem Text="es" Value="epaper_es.htm"></asp:ListItem>
  16.  
  17.                     <asp:ListItem Text="fr" Value="epaper_fr.htm"></asp:ListItem>
  18.  
  19.                     <asp:ListItem Text="de" Value="epaper_de.htm"></asp:ListItem>
  20.  
  21.                 </asp:DropDownList>
  22.  
  23.                 <asp:Button ID="btnGo" runat="server" Text="Go" OnClick="btnGo_Click" />
  24.  
  25.             </ItemTemplate>
  26.  
  27.         </asp:DataList>
  28.  
  29.  
  30.  
  31.  
  32.  
  33.  
  34.  
  35.     protected void btnGo_Click(object sender, EventArgs e)
  36.  
  37.     {
  38.  
  39.         try
  40.  
  41.         {
  42.  
  43.             DataListItem dli = (sender as Button).NamingContainer as DataListItem;
  44.  
  45.             if (dli != null)
  46.  
  47.             {
  48.  
  49.                 #region Get Label Text
  50.  
  51.                 Label lab = dli.FindControl("Label1") as Label;
  52.  
  53.                 if (lab != null)
  54.  
  55.                     Response.Write(lab.Text);
  56.  
  57.                 #endregion
  58.  
  59.  
  60.  
  61.                 #region Get TextBox
  62.  
  63.                 TextBox tbx = dli.FindControl("TextBox1") as TextBox;
  64.  
  65.                 if (tbx != null)
  66.  
  67.                     Response.Write(tbx.Text);
  68.  
  69.                 #endregion
  70.  
  71.  
  72.  
  73.                 #region Get DropDownList Value
  74.  
  75.                 DropDownList ddl = dli.FindControl("ddlLang") as DropDownList;
  76.  
  77.                 if (ddl != null)
  78.  
  79.                     ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Epaper", "window.open('" + ResolveUrl(ddl.SelectedValue) + "','_blank')", true);
  80.  
  81.                 #endregion
  82.  
  83.             }
  84.  
  85.         }
  86.  
  87.         catch (Exception ex)
  88.  
  89.         {
  90.  
  91.             throw ex;
  92.  
  93.         }
  94.  
  95.     }