簡體   English   中英

回發ASP后訪問選定的項目

[英]Access selected Items after Postback ASP

第一次在這里發布,所以如果有什么不適合的地方,請告訴我。 另外,我對ASP和C#的使用也不是很熟練,因此,如果我只是忽略了一些顯而易見的內容,對不起。

問題:在Page_Load中,我調用了自己的類MyGridViewExtension。 在此類的構造函數中,將創建一個Gridview。 要注意的是:在此Gridview的標題中,不僅是文字,而且是列表框。 這些列表框的使用是對顯示數據的過濾,這是通過標記列表框的一個(或多個,但不重要)選項,然后單擊回發按鈕來實現的。

我嘗試使用SelectedIndexChanged事件,但是只有在創建完GridView之后,Page_Load已經完成並且在調用它的構造函數之后才觸發。

//this is the selectedIndexChanged Event Handler
private void AddToFilterList(Object sender, EventArgs e){
    ListBox source=sender as ListBox;
    string attributeName=source.Parent.ID; //get column name
    List<string> filterList=new List<string>();
    foreach(ListItem singleFilter in Source.Items){
        if(singleFilter.Selected==true){
            filterList.Add(singleFilter.Text);
        }
    }
}
//This works

問題是,構造函數將在調用AddToFilterList之前完成,之后再也無濟於事,因為在構造函數中需要filterList。

至於其他代碼,它看起來像這樣:

public Class MyGridViewExtension(Array Data){
    checkForSelectedOptions();   //how can I have my filterList here already?
    List<string> columnNames=getAllColumnNamesByCheckingData(Data);
    //-create the template field to show the data
    foreach (string col in columnNames)
    {            
        TemplateField tfield = new TemplateField();           
        //In here, the listboxes are created     
        tfield.HeaderTemplate = new GridViewTemplate(ListItemType.Header, col, this);
        tfield.ItemTemplate = new GridViewTemplate(ListItemType.Item, col, this);
        this.Columns.Add(tfield);
    }
    this.DataSource=Data; //I actually transform the array to a datatable before, but that shouldn't matter here
}

protected void Page_Load(object sender, EventArgs e){
    Array data=getDataFromWebserver(); //works
    MyGridViewExtension thisNewGridView=new MyGridViewExtension(data);
    thisNewGridView.DataBind();
    divName.Controls.Add(thisNewGridView); //add the gridview to a div on the page
}

一切正常,獲取數據並顯示它,但是讓我受阻的是,我無法將選定的列表框項(filterList變量)放入構造函數中。

編輯:我可能應該補充一點,我應該將page_load中的代碼保持得盡可能小,因為我的工作只是擴展類,並且在調用我的類時(每次)都必須進行page_load中的每個條目,這應該保持最小。

在此先感謝潛在的答案,評論(和編輯,因為我的帖子可能不如我希望的那樣好)。 我已經進行了大量的編輯,因為我忽略了一些重要的內容。 對所有已經嘗試理解/回答的人表示抱歉。

最后編輯:我通過為整個GridView重新啟用ViewState,從而在某種程度上解決了該問題,這引起了一些重要的問題。 但是,這些問題比此處描述的問題更容易解決,因此這可能是更好的方法。
感謝所有提供提示的人。

protected void Page_Load(object sender, EventArgs e)
{
    Array data;
    if (IsPostback)
    {
        data = Session["data"] == null ? getDataFromWebserver() : Session["data"] // if session is null, go get data, otherwise use session variable.
    }
    else
    {
        // Go get you data, since it is a first load or a refresh
        // once you have data - put it in session
        Session["data"] =  getDataFromWebserver(); 
        data = Session["data"];
    } 

    MyGridViewExtension thisNewGridView=new MyGridViewExtension(data);
    thisNewGridView.DataBind();
    divName.Controls.Add(thisNewGridView); //add the gridview to a div on the page

    // No you can do whatever you need to do...
    // some code
}

試試這個,看看是否有幫助。

這可行。 它會加載一個下拉列表,您可以從中選擇一個項目,然后在該項目上過濾數據。 這就是您所描述的,或者至少是我的理解方式。 下拉列表可能代替了您的列表框,但是,我認為ddl看上去更簡潔(不過個人喜好)。

后台代碼:

    using xxx.DB;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.IO;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    namespace xxx_Internal_SQL.PostTree.Reports.FailedLeads
    {
        public partial class Default : System.Web.UI.Page
        {
            private string programName = "Post_Reports_FailedLeads";

            private List<string> lstTransactionSource = new List<string>();
            private List<string> lstTransactionSubSource = new List<string>();
            private List<string> lstTransactionRef = new List<string>();
            private List<string> lstTransactionSubRef = new List<string>();
            private List<string> lstIsTest = new List<string>();

            private string TransactionSource = string.Empty;
            private string TransactionSubSource = string.Empty;
            private string TransactionRef = string.Empty;
            private string TransactionSubRef = string.Empty;
            private string IsTest = string.Empty;

            protected void Page_Load(object sender, EventArgs e)
            {
                try
                {
                    if (IsPostBack)
                    {
                        if (Session["myDataView"] != null)
                            BindDataToGV((DataView)Session["myDataView"]);
                    }
                    else
                    {
                        FillDDL();
                        ViewState["sortOrder"] = "";
                        Session["OriginalDT"] = null;
                    }
                }
                catch (Exception ex)
                {
                    Global.ReportProblem(ex, programName, "Page_Load");
                }
            }

            private void FillTable(string sortExp, string sortDir)
            {
                try
                {
                    ClearGV();

                    object myData;
                    DataTable dtData = GetData();
                    Session["OriginalDT"] = dtData;

                    if (sortExp != string.Empty)
                    {
                        DataView myDataView = new DataView();
                        myDataView = dtData.AsDataView();

                        myDataView.Sort = string.Format("{0} {1}", sortExp, sortDir);

                        dtData = myDataView.ToTable();
                        Session["OriginalDT"] = dtData;
                        Session["myDataView"] = myDataView;

                        myData = myDataView;
                    }
                    BindDataToGV(dtData);
                }
                catch (Exception ex)
                {
                    Global.ReportProblem(ex, programName, "FillTable");
                }
            }

            private DataTable GetData()
            {
                return GetData(db, values);
            }
            private void ClearGV()
            {
                gvTransactions.DataSource = null;
                gvTransactions.DataBind();
            }
            private void BindDataToGV(object obj)
            {

                gvTransactions.DataSource = obj;
                gvTransactions.DataBind();
            }
            private DataTable GetData(Database db, SortedList<string, string> values)
            {
                DataTable dt = null;

                try
                {
                    if (db.GenericSP("sp_xxx", values, true))
                        return db.Output_DT;
                }
                catch (Exception ex)
                {
                    Global.ReportProblem(ex, programName, "GetData");
                }

                return dt;
            }
            protected void lnkFindTransactions_Click(object sender, EventArgs e)
            {
                try
                {
                    if (ddlAffiliates.SelectedIndex > 0) FillTable("", "");
                }
                catch (Exception ex)
                {
                    Global.ReportProblem(ex, programName, "lnkFindTransactions_Click");
                }
            }
            protected void gvTransactions_Sorting(object sender, GridViewSortEventArgs e)
            {
                FillTable(e.SortExpression, sortOrder);
            }
            protected void gvTransactions_PageIndexChanging(object sender, GridViewPageEventArgs e)
            {
                gvTransactions.PageIndex = e.NewPageIndex;

                if (Session["OriginalDT"] != null)
                    BindDataToGV((DataTable)Session["OriginalDT"]);
            }
            public string sortOrder
            {
                get
                {
                    if (ViewState["sortOrder"].ToString() == "desc")
                    {
                        ViewState["sortOrder"] = "asc";
                    }
                    else
                    {
                        ViewState["sortOrder"] = "desc";
                    }

                    return ViewState["sortOrder"].ToString();
                }
                set
                {
                    ViewState["sortOrder"] = value;
                }
            }
            private void FillDDL()
            {
                if (db.GetRecords("sp_xxx"))
                {
                    DataTable dt = db.Output_DT;

                    ddlAffiliates.Items.Add(new ListItem("Select...", ""));
                    foreach (DataRow dr in dt.Rows)
                        ddlAffiliates.Items.Add(new ListItem(dr["name"].ToString(), dr["aid"].ToString()));
                }
            }
        }
    }

前端:

        <asp:Table runat="server">
            <asp:TableRow>
                <asp:TableCell Width="100px" HorizontalAlign="Right">Date: </asp:TableCell>
                <asp:TableCell Width="200px" HorizontalAlign="Left">
                    <ajaxToolkit:CalendarExtender runat="server" Animated="true"
                        ID="extCalendarEnd" TargetControlID="txtDateEnd">
                    </ajaxToolkit:CalendarExtender>
                    <asp:TextBox ID="txtDateEnd" runat="server" Width="180px"></asp:TextBox>
                </asp:TableCell>
                <asp:TableCell Width="75px" HorizontalAlign="Left">Seller: </asp:TableCell>
                <asp:TableCell Width="200px" HorizontalAlign="Left">
                    <asp:DropDownList ID="ddlAffiliates" runat="server" Enabled="false"></asp:DropDownList>
                </asp:TableCell>
                <asp:TableCell HorizontalAlign="Left">
                    <asp:UpdatePanel runat="server" UpdateMode="Always" ID="upnlFind" ChildrenAsTriggers="true">
                        <ContentTemplate>
                            <asp:LinkButton ID="lnkFindTransactions" runat="server" CssClass="linkButton" OnClick="lnkFindTransactions_Click" Text="Find" />
                        </ContentTemplate>
                    </asp:UpdatePanel>
                </asp:TableCell>
            </asp:TableRow>
            <asp:TableRow>
                <asp:TableCell ColumnSpan="5">
                    <hr />
                    <asp:Panel runat="server" Width="600px" Height="100%">
                        <asp:Panel runat="server" ID="pnlGridview" Width="500px" Style="margin: 0px auto 0px auto;">
                            <asp:GridView runat="server" ID="gvTransactions"
                                GridLines="None" AllowPaging="True"
                                AllowSorting="True" PageSize="25"
                                CellPadding="4" ForeColor="#333333"
                                Width="600px" OnSorting="gvTransactions_Sorting"
                                OnPageIndexChanging="gvTransactions_PageIndexChanging"
                                RowStyle-Wrap="false" CssClass="gvTransactions">
                                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                                <PagerSettings Position="TopAndBottom" Mode="NumericFirstLast" />
                                <PagerStyle HorizontalAlign="Left" />
                                <EditRowStyle BackColor="#999999" />
                                <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                                <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                                <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                                <SortedAscendingCellStyle BackColor="#E9E7E2" />
                                <SortedAscendingHeaderStyle BackColor="#506C8C" />
                                <SortedDescendingCellStyle BackColor="#FFFDF8" />
                                <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
                            </asp:GridView>
                        </asp:Panel>
                    </asp:Panel>
                </asp:TableCell>
            </asp:TableRow>
        </asp:Table>

作為結束語。 它並不是完美的所有尋址代碼,但是可以完成其設計目標。 隨時在其頂部構建或修改其任何部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM