2013-03-19 29 views
3

填充的列表框像这样:列表框Selected.value抛出空例外

if (ds != null) 
{ 
    ListPreviousRecords.Items.Clear(); 

    ListPreviousRecords.DataSource = ds; 
    ListPreviousRecords.DataTextField = "Date"; 
    ListPreviousRecords.DataValueField = "ID"; 
    ListPreviousRecords.DataBind(); 
} 

获取选定值:

protected void ListPreviousRecords_OnSelectedIndexChanged(object sender, EventArgs e) 
{ 
    if(ListPreviousRecords.SelectedItem.Value != "") 
    { 
     int mySelectedValue = int.Parse(ListPreviousRecords.SelectedItem.Value);// throwing null exception 
     loadPreviousDetails(mySelectedValue); 
    } 
} 
+0

检查,如果SelectedItem.Value是。否则,你可能会遇到你的if语句,其中的空值导致你的异常。 – 2013-03-19 10:46:39

回答

6

可以为了确保不加验证码空值输入

if(!string.IsNullOrEmpty(ListPreviousRecords.SelectedItem.Value)) 
{ 
... 
} 

,并确保AutoPostBack="true"是在你的控制设置

链接:http://msdn.microsoft.com/fr-fr/library/system.string.isnullorempty.aspx

+1

我不确定,但我认为抛出null异常是因为'SelectedItem'可能为空,并且他试图获取它的'.Value'。 – 2013-03-19 10:46:40

+0

Linus因为您必须确保您的控件在更改值时发布,对于此案例添加AutoPostBack属性 – 2013-03-19 10:48:59

+0

感谢Frederique ..... – Veer 2013-04-12 08:56:00

0

使用ListPreviousRecords.SelectedValue

if (!string.IsNullOrWhiteSpace(ListPreviousRecords.SelectedValue)) { 
    // ... 
} 
1

变化:

if(ListPreviousRecords.SelectedItem.Value != "") 

为: '!= NULL'

if (!string.IsNullOrEmpty(ListPreviousRecords.SelectedItem))