【发布时间】:2014-08-25 19:16:18
【问题描述】:
我不知道如何在数据绑定后设置我选择的值。我将值存储在临时变量中,然后在绑定后再次设置它,但它不起作用。
代码背后
protected void InsertButton_Click(object sender, EventArgs e)
{
var ctrl = (Control)sender;
var lvl = (ListViewItem)ctrl.NamingContainer;
var formSectionListBox = (ListBox)lvl.FindControl("formsection");
var temp = formSectionListBox.SelectedValue;
// Update ListView
ListView1.DataSource = SqlDataSource1;
ListView1.DataBind();
formSectionListBox.Items.FindByValue(temp).Selected = true;
}
ASP.net
<asp:ListView ID="ListView1" runat="server" InsertItemPosition="FirstItem" OnPagePropertiesChanged="ListView1_PagePropertiesChanged" OnItemEditing="ListView1_OnItemEditing" DataKeyNames="FormTitle" OnSelectedIndexChanged="ListView1_SelectedIndexChanged" OnItemCanceling="ListView1_OnItemCanceling" OnItemUpdating="ListView1_ItemUpdating" OnItemInserting="ListView1_ItemInserting" OnItemDeleting="ListView1_ItemDeleting">
<InsertItemTemplate>
<tr>
<td>
<asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Insert" OnClick="InsertButton_Click" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Clear" CausesValidation="False" />
</td>
<td>
<div style="height: auto; width: 250px; overflow: auto; border: solid; border-color: ActiveBorder">
<asp:ListBox ID="formsection" runat="server" DataSourceID="FormSectionDataSource" DataTextField="FormSection" DataValueField="FormSectionID" AppendDataBoundItems="True" SelectedValue='<%# Bind("FormSectionID") %>' Height="150px">
<asp:ListItem Value=""><- please select -></asp:ListItem>
</asp:ListBox>
</div>
</td>
</tr>
</InsertItemTemplate>
</asp:ListView>
【问题讨论】:
-
从
ItemCreated方法中进行选择。详情请看this SO Question。 -
您的 CodeBehind 甚至与 ASPX 不匹配。请不要发布不必要的代码 - 例如 CSS、formSectionListBox 和 ListView。相反,请发布您从哪个事件访问这些代码。
标签: c# asp.net bind selectedvalue