2014-06-30 94 views
0

第一次發佈在這裏,所以如果有東西不適合,讓我知道。此外,我對ASP和C#不是很有經驗,所以如果我忽略了一些明顯的東西,我很抱歉。訪問所選項目後回發ASP

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

我嘗試使用SelectedIndexChanged事件,但只有在Page_Load已完成後觸發,並且在我的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 

的問題是,該構造將完成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,這會導致一些壓倒一切的問題。但是這些比這裏描述的問題更容易處理,所以這可能是更好的路線。
感謝大家給了小費。

+0

創建自己定製的'GridView'的任何理由? – Bharadwaj

+0

添加更多的過濾,排序和顯示功能,並給它一些特殊的變量(例如,能夠告訴它,它應該讓第3列顯示只是通過去「my ... thisview = new我的...(); thisview.columnToHide = 3;) 總體原因是一個webtool,程序員厭倦了爲每個不同的頁面/數據集創建這樣的函數,所以需要一個泛型類,可用 – LindenRathan

+0

發生了什麼事情,你創建了自己的'GridView',這很好:)但是你重新創建並添加了每個'Page_Load',所以前面的'GridView'值你所想要的會丟失。 't get what what before before。 – Bharadwaj

回答

0
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 
} 

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

This Works。它會加載一個下拉列表,您可以從中選擇一個項目,在該項目上過濾數據。這就是你所描述的,或者至少是我理解它的方式。下拉列表可能會替代您的列表框,但是,我認爲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> 

的閉注。這不是一個完美的所有尋址代碼,但它完成了它設計的目的。隨意構建它的頂部或修改它的任何部分。

+0

對不起,但這讓我們完整的gridview消失,因爲我經常回發並且沒有viewstate設置。雖然我將不得不改變這個問題,因爲我已經改變了我的代碼中的某些內容,現在還有另一個問題。抱歉佔用你的時間。 – LindenRathan

+0

盡我所知,你應該得到你的數據,把它的副本放在會話中,然後做你的工作。對於每次回發,您應該從會話中重新加載它,然後調用您的事件。 –

+0

我現在改變了這個問題,因爲我自己很大程度上誤解了一些東西。由於問題是我需要我的事件在我的Page_load完成之前觸發(本身不可能,據我所知),您的答案可能無濟於事,儘管我仍然有可能誤解別的東西。 – LindenRathan