在 WebForm 之間傳遞參數利用 QueryString 和 Session 來練習傳遞參數
using System.Data; namespace PassPara { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { DataTable dt = new DataTable("Demo"); dt.Columns.Add("ProdNO", typeof(int)); dt.Columns.Add("ProdName", typeof(string)); dt.Rows.Add(1, "Visial Studio 2013"); dt.Rows.Add(2, "SQL Server 2014"); dt.Rows.Add(3, "Windows Server 2012 R2"); dt.Rows.Add(4, "Office 365"); dt.Rows.Add(5, "Windows Azure"); gvData.DataSource = dt; gvData.DataBind(); } } protected void btnShowData_Click(object sender, EventArgs e) { // 避免重覆選取,要先把 Text 內容清空 lblResult.Text = ""; // 利用 foreach 方式來搜尋使用者勾選資料 foreach (GridViewRow row in gvData.Rows) { // 確認 RowType 是 DataRow if (row.RowType != DataControlRowType.DataRow) continue; // 利用 FindControl 來找到 CheckBox 控件 CheckBox cb = row.FindControl("cbChecked") as CheckBox; if (cb == null || !cb.Checked) continue; lblResult.Text += row.Cells[2].Text + "<br>"; } } private List<string> getCheck(GridView gvData) { // 利用 LINQ 方式找出使用者勾選資料 List<string> checkresult = (from GridViewRow r in gvData.Rows where (r.FindControl("cbChecked") as CheckBox).Checked == true select gvData.Rows[r.RowIndex].Cells[2].Text.ToString()).ToList<string>(); return checkresult; } protected void btnQueryString_Click(object sender, EventArgs e) { Response.Redirect("QueryStringPage.aspx?Data=" + Server.UrlEncode(string.Join(",", getCheck(gvData)))); } protected void btnSession_Click(object sender, EventArgs e) { Session["Data"] = getCheck(gvData); Response.Redirect("SessionPage.aspx"); } } }
QuerString 作法
// SessionPage.aspx.cs 內容 namespace PassPara { public partial class SessionPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { gvResult.DataSource = Session["Data"] as List<string>; gvResult.DataBind(); gvResult.HeaderRow.Cells[0].Text = "勾選選項"; } } } // SessionPage.aspx 內容 <body> <form id="form1" runat="server"> <div> <h1>利用 QueryString 傳遞參數</h1> QueryString 參數內容: <%=Server.UrlDecode(Request.QueryString["Data"]) %><br/> <br/> </div> <asp:GridView ID="gvResult" runat="server"> </asp:GridView> <br/> <asp:HyperLink ID="Hyperlink1" runat="server" NavigateUrl="~/Default.aspx">回首頁</asp:HyperLink> </form> </body>
Session 作法
// SessionPage.aspx.cs namespace PassPara { public partial class SessionPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { gvResult.DataSource = Session["Data"] as List<string>; gvResult.DataBind(); gvResult.HeaderRow.Cells[0].Text = "勾選選項"; } } } // SessionPage.aspx <body> <form id="form1" runat="server"> <div> <h1>利用 session 傳遞參數</h1> session 參數內容: <%= string.Join(",",Session["Data"] as List<string>) %><br /> <br /> </div> <asp:GridView ID="gvResult" runat="server"> </asp:GridView> <br /> <asp:HyperLink ID="Hyperlink1" runat="server" NavigateUrl="~/Default.aspx">回首頁</asp:HyperLink> </form> </body>
沒有留言:
張貼留言