第一次在这里发帖,所以如果某些内容不适合,请告诉我。我对ASP和C#也没有太多经验,所以如果我忽视了一些明显的东西,我很抱歉。
问题: 在Page_Load中,我调用自己的类MyGridViewExtension。在此类的构造函数中,将创建Gridview。问题是:在Gridview的Headers中不仅是Literal,还有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中的代码,因为我的工作只是Extension类,并且当我的类被调用时,必须(每次)调用page_load中的每个条目,应该保持在最低限度。提前感谢您的潜在答案,评论(以及编辑,因为我的帖子可能并不像我希望的那样好)。 我已经编辑过很多,因为我忽略了一些重要的事情;对所有已经尝试理解/回答的人表示抱歉。
最后编辑:我通过为整个GridView重新启用ViewState来解决这个问题,这会导致一些重要的问题。但是那些比这里描述的问题更容易处理,所以这可能是更好的路线 感谢所有给出提示的人。
答案 0 :(得分: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
}
试试这个,看看是否有帮助。
这很有效。它会加载一个下拉列表,您可以从中选择要过滤数据的项目。这就是你所描述的,或者至少我理解它的方式。下拉列表可能会替换您的列表框,但是,我认为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>
作为结束语。它不是一个完美的所有寻址代码,但它完成了它的设计目的。随意构建它或修改它的任何部分。