C# 回发ASP后访问所选项目

C# 回发ASP后访问所选项目,c#,asp.net,C#,Asp.net,第一次在这里发帖,如果有不合适的地方,请告诉我。另外,我对ASP和C#不是很有经验,所以如果我忽略了一些显而易见的东西,我很抱歉 问题是: 在页面加载中,我调用自己的类MyGridViewExtension。在此类的构造函数中,将创建Gridview。问题是:在这个Gridview的标题中,不仅是一个文本,而且是一个列表框。这些列表框的用途是过滤显示的数据,这是通过标记列表框的一个(或多个,但这并不重要)选项,然后单击回发按钮来实现的 我试图处理SelectedIndexChanged事件,但只

第一次在这里发帖,如果有不合适的地方,请告诉我。另外,我对ASP和C#不是很有经验,所以如果我忽略了一些显而易见的东西,我很抱歉

问题是: 在页面加载中,我调用自己的类MyGridViewExtension。在此类的构造函数中,将创建Gridview。问题是:在这个Gridview的标题中,不仅是一个文本,而且是一个列表框。这些列表框的用途是过滤显示的数据,这是通过标记列表框的一个(或多个,但这并不重要)选项,然后单击回发按钮来实现的

我试图处理SelectedIndexChanged事件,但只有在页面加载完成后,以及在其中调用构造函数时,在创建GridView之后,才会触发该事件

//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
//这是selectedIndexChanged事件处理程序
私有void AddToFilterList(对象发送方,事件参数e){
ListBox source=发送方作为ListBox;
string attributeName=source.Parent.ID;//获取列名
列表过滤器列表=新列表();
foreach(Source.Items中的ListItem singleFilter){
if(singleFilter.Selected==true){
filterList.Add(singleFilter.Text);
}
}
}
//这很有效
问题是,构造函数将在调用AddToFilterList之前完成,而在调用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
}
公共类MyGridViewExtension(数组数据){
checkForSelectedOptions();//我怎么能在这里有我的过滤器列表呢?
List columnNames=getAllColumnNamesByCheckingData(数据);
//-创建模板字段以显示数据
foreach(列名称中的字符串列)
{            
TemplateField tfield=新TemplateField();
//在这里,将创建列表框
tfield.HeaderTemplate=新的GridViewTemplate(ListItemType.Header,col,this);
tfield.ItemTemplate=新的GridViewTemplate(ListItemType.Item,col,this);
this.Columns.Add(tfield);
}
this.DataSource=Data;//我以前确实将数组转换为datatable,但这在这里并不重要
}
受保护的无效页面加载(对象发送方、事件参数e){
数组数据=getDataFromWebserver();//有效
MyGridViewExtension thisNewGridView=新的MyGridViewExtension(数据);
thisNewGridView.DataBind();
divName.Controls.Add(thisNewGridView);//将gridview添加到页面上的div中
}
一切正常,获取数据并显示数据,但阻碍我的是我无法将列表框的选定项(filterList变量)放入构造函数

编辑:我可能应该补充一点,我应该在页面加载中保存尽可能小的代码,因为我的工作只是扩展类,页面加载中的每个条目都必须在调用我的类时进行(每次),这应该保持在最小值

提前感谢您提供的潜在答案、评论(和编辑,因为我的帖子可能没有我希望的那么好)。 我已经做了大量的编辑,因为我忽略了一些重要的东西;对于所有试图理解/回答的人,我深表歉意

最后一次编辑:我通过为整个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()));
                }
            }
        }
    }
使用xxx.DB;
使用制度;
使用System.Collections.Generic;
使用系统数据;
使用System.IO;
使用System.Linq;
使用System.Web;
使用System.Web.UI;
使用System.Web.UI.WebControl;
命名空间xxx\u Internal\u SQL.postree.Reports.FailedLeads
{
公共部分类默认值:System.Web.UI.Page
{
私有字符串programName=“Post\u Reports\u FailedLeads”;
私有列表lstTransactionSource=新列表();
私有列表lstTransactionSubSource=新列表();
私有列表lstTransactionRef=新列表();
私有列表lstTransactionSubRef=新列表();
私有列表lsistest=新列表();
私有字符串TransactionSource=string.Empty;
私有字符串TransactionSubSource=string.Empty;
私有字符串TransactionRef=string.Empty;
私有字符串TransactionSubRef=string.Empty;
私有字符串IsTest=string.Empty;
受保护的无效页面加载(对象发送方、事件参数e)
{
尝试
{
如果(iPostBack)
{
如果(会话[“myDataView”]!=null)
BindDataToGV((DataView)会话[“myDataView”]);
}
其他的
{
FillDDL();
视图状态[“排序器”]=“”;
会话[“OriginalDT”]=null;
}
}
捕获(例外情况除外)
{
全局.ReportProblem(例如,程序名,“页面加载”);
}
}
专用空白填充表(字符串SORTXP、字符串sortDir)
{
尝试
{
ClearGV();
对象myData;
DataTable dtData=GetData();
会话[“OriginalDT”]=dtData;
if(sortExp!=string.Empty)
{
        <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>