在ListView' ItemDataBound
中,我有一个DropDownList控件。 DropDownList填充在ListView
的{{1}}方法中(我发现只有这样才能在EditTemplate中填充列表...... DropDownList只存在于EditTemplate中;它必须是一个标签在ItemTemplate
)。
列表填充,一切正常。我遇到的问题是,当单击“更新”按钮并调用ItemUpdating
方法时,DropDownList的SelectedIndex
总是为零,无论选择哪个值时间。
aspx代码减去额外的模板如下所示:
<asp:ListView ID="ListView1" runat="server" OnItemDataBound="ListView1_ItemDataBound" OnItemUpdating="ListView1_ItemUpdating" OnItemEditing="ListView1_ItemEditing">
<EditItemTemplate>
<tr style="">
<td><asp:DropDownList CssClass="vaultDropDownList" ID="EditStaffList" runat="server" AutoPostBack="false" CausesValidation="True"></asp:DropDownList></td>
<td>
<asp:LinkButton ID="UpdateButton" runat="server" CommandName="Update" Text="Update" />
<asp:LinkButton ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" />
</td>
</tr>
</EditItemTemplate>
</asp:ListView>
代码隐藏:
protected void ListView1_ItemEditing(object sender, ListViewEditEventArgs e)
{
ListView1.EditIndex = e.NewEditIndex;
}
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.DisplayIndex == ListView1.EditIndex)
{
DropDownList ddl = e.Item.FindControl("EditStaffList") as DropDownList;
BindDropDownList(ddl);
}
}
protected void ListView1_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
DropDownList staff = ListView1.Items[e.ItemIndex].FindControl("EditStaffList") as DropDownList;
//SQL update stuff will go here
ListView1.EditIndex = -1;
}
如果我尝试在Page_Load
方法中填充DropDownList以使用IsPostBack
,则下拉控件始终返回null
。
任何帮助都非常感谢!
编辑:ListView绑定:
protected void DisplayListView(object sender, EventArgs e)
{
string connString = SQLstringTooLong;
SqlConnection sqlConnection = new SqlConnection(connString);
DataTable initialTable = new DataTable();
string queryStatement = "SELECT lotsastuff";
SqlDataAdapter dataAdapter = new SqlDataAdapter(queryStatement, sqlConnection);
dataAdapter.Fill(initialTable);
ListView1.DataSource = initialTable;
ListView1.DataBind();
}
Edit2:这是dropdownlist绑定方法:
public static void CreateStaffList(DropDownList list, string searchGroup)
{
ArrayList userList = new ArrayList();
//more SQL stuff
list.DataSource = userList;
list.DataBind();
}
答案 0 :(得分:0)
确保您不会在每个PostBack上绑定ListView。把它包裹起来以检查它。
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DisplayListView();
}
}
如果您不这样做,您的整个ListView(包括DropDownLists)都会重新绑定。这会导致DropDownList将其SelectedIndex重置为0。