c# - 列表框 Selected.value 抛出 null 异常

标签 c# asp.net listbox

像这样填充的列表框:

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);
    }
}

最佳答案

您可以添加此代码以确保输入的不是空值

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

并确保在您的控件上设置了 AutoPostBack="true"

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

关于c# - 列表框 Selected.value 抛出 null 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15497199/

相关文章:

c# - 检查用户是否在文本框中写入文本

c# - 打开 mysql 连接时出现 System.TypeInitializationException 错误

c# - 在 mvc 之类的文件夹中而不是站点根目录中的 Webform 路由主页

wpf - ListBox+WrapPanel 方向键导航

wpf - 当鼠标悬停在任何内容上时,如何使ScrollViewer滚动

c# - 删除右键单击事件的 ListBoxItem 背景

c# - 从文件名中删除非法字符以刻录到 CD 上

c# - 为什么 Socket.Receive 在超时设置为无限时在半关闭连接上超时?

c# - 在 Visual Studio 2010 或更高版本中粘贴重复 ID 时,我可以更改控件的自动命名吗

c# - 如何使 .NET Core 6 顶级语句模板异步?