2013年6月27日 星期四

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

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


C#:
    private void CopyFileToNetwork()
    {
        System.IO.StreamReader sErr;
        System.IO.StreamReader sOut;
        String tempErr, tempOut;
        System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
        myProcess.StartInfo.FileName = @"NET";
        myProcess.StartInfo.Arguments = "USE Y: \\\\192.168.0.136\\folder001 \"123456\" /user:\"Administrator\""; //password is 123456, username is Administrator
        myProcess.StartInfo.CreateNoWindow = true;
        myProcess.StartInfo.UseShellExecute = false;
        myProcess.StartInfo.RedirectStandardError = true;
        myProcess.StartInfo.RedirectStandardOutput = true; // 導出 StandardOutput
        try
        {
            myProcess.Start();
            myProcess.WaitForExit(10000);

            if (!myProcess.HasExited)
            {
                myProcess.Kill();
                Response.Write("執行失敗!!");
            }
            else
            {
                sErr = myProcess.StandardError;
                tempErr = sErr.ReadToEnd();
                sErr.Close();

                sOut = myProcess.StandardOutput;
                tempOut = sOut.ReadToEnd();
                sOut.Close();

                if (myProcess.ExitCode == 0) //連線磁碟機建立成功
                {
                    //Response.Write("執行成功" + "<BR>" + tempOut.ToString()); // 把執行結果也印出來
                    System.IO.File.Copy(@"D:\abc.xls", @"Y:\abc.xls",true);
                }
                else if (myProcess.ExitCode == 2) // 忽略連線磁碟機已存在
                {
                    System.IO.File.Copy(@"D:\abc.xls", @"Y:\abc.xls", true);
                }
                else
                {
                    Response.Write(tempErr);
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
            myProcess.Close();
        }
        finally
        {
            myProcess.Close();
        }
    }

2013年6月17日 星期一

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

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


HTML:
<form id="form1" runat="server">
<div>
    <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>
</form>

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_tsUrlReferrer : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            ViewState["UrlReferrer"] = "";
            if (!IsPostBack)
            {
                if (Request.UrlReferrer != null)
                    ViewState["UrlReferrer"] = Request.UrlReferrer.ToString();
            }
            Label1.Text = ViewState["UrlReferrer"].ToString();
        }
        catch (Exception ex)
        {
            throw ex;
        }
     
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            Response.Redirect(ViewState["UrlReferrer"].ToString());
        }
        catch (Exception)
        {
         
            throw;
        }
     
    }
}

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#:
string strScript = "alert(\"建立完成!\");";
ScriptManager.RegisterStartupScript(this, typeof(string), "ALERT", strScript, true);

string strScript = "<script>alert(\"建立完成!\");</script>";
this.Page.Controls.Add(new LiteralControl(str_Script));

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

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


HTML:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:KMSConnectionString %>"
            InsertCommand="INSERT INTO category(cat001, cat002, objactive, objcreate) VALUES (@cat001,@cat002,@objactive,@objcreate);select @ID=@@Identity
" oninserted="SqlDataSource1_Inserted">
<InsertParameters>
                <asp:ControlParameter Name="cat001" ControlID="cat001" Type="String" />
                <asp:Parameter Name="cat002" DefaultValue="Folder" Type="String" />
                <asp:ControlParameter Name="objactive" ControlID="objactive" Type="String" />
                <asp:Parameter Name="objcreate" Type="String" />
                <asp:Parameter Name="ID" Direction="InputOutput" Type="Decimal" />
            </InsertParameters>
        </asp:SqlDataSource>

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

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

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


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

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

ASP.NET 取得Windows驗証Login ID

ASP.NET 取得Windows驗証Login ID


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

SQL 列出資料庫中所有的Table

SQL 列出資料庫中所有的Table


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

Access:
SELECT * FROM MSYSOBJECTS

Oracle:
SELECT * FROM USER_OBJECTS

ASP.NET ListBox 互傳

ASP.NET ListBox 互傳


HTML:
<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple">
    <asp:ListItem>a</asp:ListItem>
    <asp:ListItem>b</asp:ListItem>
    <asp:ListItem>c</asp:ListItem>
</asp:ListBox>
<asp:Button ID="Button1" runat="server" Text="Add" onclick="Button1_Click" />

<asp:ListBox ID="ListBox2" runat="server" SelectionMode="Multiple">
</asp:ListBox>
<asp:Button ID="Button2" runat="server" Text="Del" onclick="Button2_Click" />

C#:
    protected void Button1_Click(object sender, EventArgs e)
    {
        //單選add時用下列這行
        //ListBox2.Items.Add(ListBox1.SelectedItem);

        //多選add用迴圈
        for (int i = 0; i < ListBox1.Items.Count; i++)
        {
            if (ListBox1.Items[i].Selected)
            {
                ListBox2.Items.Add(ListBox1.Items[i]);
            }
        }
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        //單選del
        //ListBox2.Items.RemoveAt(ListBox2.SelectedIndex);

        //多選del用迴圈
        for (int i = ListBox2.Items.Count - 1; i >= 0; i--)
        {
            if (ListBox2.Items[i].Selected)
            {
                ListBox2.Items.RemoveAt(i);
            }
        }
    }

2013年6月6日 星期四

ASP.NET DropDownList 尋找符合項目

ASP.NET DropDownList 尋找符合項目


C#:
protected void Page_Load(object sender, EventArgs e)
{
    //由於DropDownList只能單選,為了避免錯誤,先將已選定的項目取消
    this.DropDownList1.Items[DropDownList1.SelectedIndex].Selected = false;

    //尋找符合"1"的項目
    ListItem item=this.DropDownList1.Items.FindByValue("1");

    //如果在DropDownList清單中有找到相符的,則將它改成被選取的項目
    if(item!=null)item.Selected = true;
}

2013年6月5日 星期三

C# ASCII字碼轉換應用

C# ASCII字碼轉換應用

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

C#:
    int intAsciiCode = Int32.Parse(RetAsciiCode(“A”)); //回傳數字65
    string strAsciiChar = RetAsciiChar(65);  //回傳大寫A

    public int RetAsciiCode(string MyString)
    {
        if (MyString.Length == 0)
            return 0;
        else if (MyString.Length > 1)
            MyString = MyString[0].ToString();

        int AsciiCodeO = (int)System.Convert.ToChar(MyString);
        byte[] AsciiCodeB = System.Text.Encoding.ASCII.GetBytes(MyString);
        //int AsciiCode = System.Convert.ToInt32(AsciiCodeB);
        return AsciiCodeO;
    }

    public string RetAsciiChar(int AsciiCode)
    {
        return System.Convert.ToChar(AsciiCode).ToString();
    }

C# Get MAC Address

Get MAC Address C#

C#
    public string GetMACAddress()
    {
        ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
        ManagementObjectCollection moc = mc.GetInstances();
        string MACAddress = String.Empty;
        foreach (ManagementObject mo in moc)
        {
            if (MACAddress == String.Empty) // only return MAC Address from first card
            {
                if ((bool)mo["IPEnabled"] == true) MACAddress = mo["MacAddress"].ToString();
            }
            mo.Dispose();
        }
        return MACAddress;
    }

ASP.NET Encrypt Excel加密

ASP.NET Encrypt Excel加密

C#:
private void EncryptExcel(string FileName)
    {
        try
        {
            FileName = @"D:\Inetpub\PORTAL\Test\MyFilests.xlsx";

            Microsoft.Office.Interop.Excel.Application xlApp = null;
            Workbook wb = null;
            Worksheet ws = null;
            Range aRange = null;
            xlApp = new Microsoft.Office.Interop.Excel.Application();

            //打開Server上的Excel檔案
            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);
            //第一個Workbook
            wb = xlApp.Workbooks[1];
            //設密碼
            wb.Password = "123456";
            //另存新檔
            wb.SaveAs(@"D:\Inetpub\PORTAL\Test\NewPasswordx.xlsx");
            //取得worksheet
            ws = (Worksheet)wb.Worksheets[1];
            Label1.Text = ws.Name;
            //開啟檔案
            System.Diagnostics.Process.Start(@"D:\Inetpub\PORTAL\Test\NewPasswordx.xlsx");

        }
        catch (Exception)
        {

            throw;
        }
    }

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:
<script language="javascript" type='text/javascript'>

        function body_onKeyDown() {
            if (window.event.keyCode == 13) {
                alert(event.type);
                document.all.ImageButton1.focus();
                newWindow = window.open("http://www.google.com", "SelectUser", "width=500,height=500");
                newWindow.focus();
            }
        }
    </script>

HTML:
<body onkeydown="body_onKeyDown()">
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
        <asp:ImageButton ID="ImageButton1" runat="server"
            onclick="ImageButton1_Click" />
    </div>
    </form>
</body>

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_tsOnKeyDown : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Redirect("http://www.yahoo.com.tw");
    }
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("http://www.msn.com.tw");
    }
}

ASP.NET Dynamic InnerHTML

ASP.NET Dynamic InnerHTML

HTML:
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Inner" OnClick="Button1_Click" />
    </div>
    <div id="dynamic1">
    </div>
    <div id="dynamic2" runat="server">
    </div>
    </form>
</body>

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_tsInnerHTML : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
     
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            //Script
            string strScript = "document.getElementById('dynamic1').innerHTML='<input type=\"file\" name=\"FileUpload1\" id=\"FileUpload1\" />'";
            ScriptManager.RegisterStartupScript(this, typeof(string), "Function", strScript, true);
            //Asp.net
            dynamic2.InnerHtml = Server.HtmlDecode("<Input type='file' name='fileupload2' id='fileupload2'>");
        }
        catch (Exception)
        {
            throw;
        }
    }
}

C# Excel to GridView

[C#]Excel to GridView

HTML:
<form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />
        <br />
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
        <asp:Label ID="lbl_Err" runat="server" Text="Label"></asp:Label><br />
        <div runat="server" clientidmode="Static" id="DIV1">
        </div>
    </div>
</form>

C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class Test_FileUpload : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
     
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            string FileFullPath = string.Empty;
            DataSet ds = null;
            DataTable dt = null;

            File_Upload flu = new File_Upload();
            flu.Set_AllowedExtension = "EXCEL";
            flu.UploadXLS(FileUpload1);
         
            ImportData imp = new ImportData();
            ds = imp.GetExcelData(flu.Get_SavePath + flu.Get_FileName);
         
            dt = ds.Tables[0];
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
        catch (Exception ex)
        {
            lbl_Err.Text = ex.Message;
        }
    }
}

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

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

web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<!--網頁PostBack後回到原來停留的位置-->
<pages maintainScrollPositionOnPostBack="true">
</pages>
</system.web>
</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#]日期相減


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_tsDateSubtract : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DateTime StartTime = DateTime.Parse("2013-05-20"); //開始日
        //DateTime EndTime = DateTime.Parse("2013-05-21"); //指定結束日
        DateTime EndTime = DateTime.Now; //當日
        TimeSpan TS = EndTime.Subtract(StartTime); //日期相減

        Response.Write(TS.Days.ToString() + "<br>");         //天(int)
        Response.Write(TS.Hours.ToString() + "<br>");        //小時(int)
        Response.Write(TS.Minutes.ToString() + "<br>");      //分(int)

        Response.Write(TS.TotalDays.ToString() + "<br>");    //天(double)
        Response.Write(TS.TotalHours.ToString() + "<br>");   //小時(double)
        Response.Write(TS.TotalSeconds.ToString() + "<br>"); //分(double)
    }
}

C# 取得Browser Language

[C#]取得Browser Language


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_tsBrowserLanguage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            HttpRequest Request = HttpContext.Current.Request;
            string browerlang = Request.UserLanguages[0].ToString();
            Response.Write(browerlang);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

C# DataTable to XML

[C#]DataTable to XML


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Xml;
using System.Xml.Linq;
using System.Text;

public partial class Test_tsDataTabletoXML : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            SqlConnection cn = new SqlConnection();
            cn.ConnectionString = "Data Source=localhost;Initial Catalog=db1;Persist Security Info=True;User ID=sa;Password=123456";

            SqlCommand cmd = new SqlCommand();
            cmd.Connection = cn;
            cmd.CommandText = "select * from Product";

            cn.Open();
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            DataSet ds = new DataSet("ds1");
            da.Fill(ds, "Product");
            DataTable dt = ds.Tables["Product"];

            // XML Setting
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = false;
            settings.Encoding = settings.Encoding = Encoding.GetEncoding("utf-8");

            // XML Write
            XElement tElement = new XElement("DataTable", "");
            using (XmlWriter xmlWriter = XmlWriter.Create("c:\\Product.xml", settings))
            {
                // Write the data set to the writer.
                tElement = DataTableToXml(dt, "root");
                tElement.WriteTo(xmlWriter);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    /// <summary>
    /// DataTable to XML
    /// </summary>
    /// <param name="pAttributeTable"></param>
    /// <param name="tParentTag"></param>
    /// <returns></returns>
    private XElement DataTableToXml(DataTable pAttributeTable, string tParentTag)
    {
        if (pAttributeTable == null)
            return null;

        XElement tParent = null;
        try
        {
            tParent = new XElement(tParentTag);  // 集合Tag的名字
            //每個DataRow為屬性分類
            foreach (DataRow tRow in pAttributeTable.Rows)
            {
                XElement tChild = new XElement("DataRow");
                //每個DataRow的DataColumn為屬性分類裡的項目
                foreach (DataColumn tColumn in pAttributeTable.Columns)
                {
                    tChild.Add(new XElement(tColumn.ColumnName, tRow[tColumn]));
                }
                tParent.Add(tChild);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return tParent;
    }
}

C# DataList取得ItemTemplate欄位值

[C#]DataList取得ItemTemplate欄位值

<asp:DataList ID="DataList1" runat="server">
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                <asp:DropDownList ID="ddlLang" runat="server">
                    <asp:ListItem Text="en" Value="epaper_en.htm"></asp:ListItem>
                    <asp:ListItem Text="tw" Value="epaper_tw.htm"></asp:ListItem>
                    <asp:ListItem Text="es" Value="epaper_es.htm"></asp:ListItem>
                    <asp:ListItem Text="fr" Value="epaper_fr.htm"></asp:ListItem>
                    <asp:ListItem Text="de" Value="epaper_de.htm"></asp:ListItem>
                </asp:DropDownList>
                <asp:Button ID="btnGo" runat="server" Text="Go" OnClick="btnGo_Click" />
            </ItemTemplate>
        </asp:DataList>



    protected void btnGo_Click(object sender, EventArgs e)
    {
        try
        {
            DataListItem dli = (sender as Button).NamingContainer as DataListItem;
            if (dli != null)
            {
                #region Get Label Text
                Label lab = dli.FindControl("Label1") as Label;
                if (lab != null)
                    Response.Write(lab.Text);
                #endregion

                #region Get TextBox
                TextBox tbx = dli.FindControl("TextBox1") as TextBox;
                if (tbx != null)
                    Response.Write(tbx.Text);
                #endregion

                #region Get DropDownList Value
                DropDownList ddl = dli.FindControl("ddlLang") as DropDownList;
                if (ddl != null)
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Epaper", "window.open('" + ResolveUrl(ddl.SelectedValue) + "','_blank')", true);
                #endregion
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }