我的ListView
里面有DropDownList
。我尝试了两种方法:在DropDownList
和OnItemDataBound
填写Page_Load
。我也试过检查PostBack
,但没有任何帮助。
当我试图获得价值时,我总是得到第一个。我明白这是因为列表被重新填充,但如何避免呢?如果我只在IsPostBack = false
时填写它们,它们就会变空。
这是我的代码:
<asp:ListView runat="server" ID="MyListView">
<LayoutTemplate>
<table border="0" cellpadding="2" cellspacing="0">
<tr>
<th><asp:Literal runat="server" Text='<%$ Resources: Resource, LabelWhole %>' /></th>
<th><asp:Literal runat="server" Text='<%$ Resources: Resource, LabelImport %>' /></th>
<th><asp:Literal runat="server" Text='<%$ Resources: Resource, LabelPeriod %>' /></th>
<th><asp:Literal runat="server" Text='<%$ Resources: Resource, LabelDate %>' /></th>
<th><asp:Literal runat="server" Text='<%$ Resources: Resource, LabelUpload %>' /></th>
</tr>
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td><%# DataBinder.Eval(Container.DataItem, "Whole") %></td>
<td><%# DataBinder.Eval(Container.DataItem, "Upload")%></td>
<td><%# DataBinder.Eval(Container.DataItem, "Period")%></td>
<td><asp:DropDownList runat="server" ID="DaysDropDownList"></asp:DropDownList></td>
<td><asp:FileUpload ID="FileUpload" runat="server" /></td>
</tr>
</ItemTemplate>
</asp:ListView>
foreach (var lvItem in MyListView.Items)
{
if (lvItem.ItemType == ListViewItemType.DataItem)
{
DropDownList dr = lvItem.FindControl("DaysDropDownList") as DropDownList;
for (int i = -1; i >= -12; i--)
{
dr.Items.Add(new ListItem(
DateTime.Now.AddMonths(i).ToString("yyyy MM"),
DateTime.Now.AddMonths(i).ToString("yyyy MM")));
}
}
}
Codebehind:
protected void Page_Load(object sender, EventArgs e)
{
this.Application.DataLayer.LoadData(UserID);
this.MyListView.DataSource = this.Application.DataLayer.Data;
this.MyListView.DataBind();
LoadDropDownLists();
}
private void LoadDropDownLists()
{
foreach (var lvItem in MyListView.Items)
{
if (lvItem.ItemType == ListViewItemType.DataItem)
{
DropDownList dr = lvItem.FindControl("DaysDropDownList") as DropDownList;
dr.Items.Clear();
for (int i = -1; i >= -12; i--)
{
dr.Items.Add(new ListItem(
DateTime.Now.AddMonths(i).ToString("yyyy MM"),
DateTime.Now.AddMonths(i).ToString("yyyy MM")));
}
}
}
}
public void SubmitButtonClick(object sender, EventArgs e)
{
foreach (var lvItem in MyListView.Items)
{
if (lvItem.ItemType == ListViewItemType.DataItem)
{
DropDownList dr = lvItem.FindControl("DaysDropDownList") as DropDownList;
FileUpload fl = lvItem.FindControl("FileUpload") as FileUpload;
if (fl.HasFile)
{
string filename = UploadFile(fl, dr.SelectedValue);
this.Application.DataLayer.SaveUploadRecord(UserID, 0, (int)UploadType.Upload, dr.SelectedValue, filename);
}
}
}
}
答案 0 :(得分:0)
使用ListItem填充DropdownList时,可以相应地设置ListItem的Selected属性。
答案 1 :(得分:0)
创建一个绑定下拉列表的函数,每次页面加载时(在page_load事件中)调用此函数,但在调用之前首先清除现有的下拉列表数据源。