我们在修改资料时,通常会遇到把读取的原数据绑定到DropDownList的情况,由于种种原因DropDownList的项目中可能已经不包含和源数据对应该的项目。
如
<asp:DropDownList ID="ddl" runat="server">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
</asp:DropDownList>
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
</asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
{
if (!IsPostBack)
{
ddl.SelectedValue = "4";
}
}
如果是这样的话,程序就会抛出异常,因为DropDownList 中并没有4这一项
那么如何避免这种情况呢
请看下面代码
ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByText("4"));
这样,如果没有在列表中找到该项目,就会返回0,也就是会选中DropDownList 的第一项,而不会抛出异常

浙公网安备 33010602011771号