Checking for null value with DataTable.Select

2.3k Views Asked by At

I'm using a DataTable select like this:

DataRow[] rows = employees.Select("Name LIKE '%" + TB_Search.Text + "%'");

LV_Employees.DataSource = rows;
LV_Employees.DataBind();

I have a listview where I'm checking a value that is contained in the datarows that I'm using in the list and I'm checking a value like this:

<%# Eval("Title") == DBNull.Value ? "" : Eval("Title") %>

But when I do this I still get this error:

Unable to cast object of type 'System.DBNull' to type 'System.String'.

I tried checking Eval("Title") == null as well and got the same error. I'm not sure how else to check for the null values that would fix this issue.

Things I've also tried that still gave the same error:

(Eval("Title") as string) ?? ""

Convert.IsDBNull(Eval("Title")) ? "" : "test"

string.IsNullOrEmpty(Eval("Title").ToString()) ? "" : "test"

Eval("Title").ToString().IsNullOrEmpty() ? "" : "test"

2

There are 2 best solutions below

1
hardkoded On BEST ANSWER

CopyToDataTable should fix the issue:

LV_Employees.DataSource = employees.Select("Name LIKE '%" + TB_Search.Text + "%'")
    .CopyToDataTable();
LV_Employees.DataBind();
2
abney317 On

Doing this in the codebehind worked, but seems weird that I can't just do the inline check in the markup code.

foreach (DataRow r in rows)
{
    if (r["Title"] == DBNull.Value)
        r["Title"] = "";
}