1

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"

abney317
  • 7,760
  • 6
  • 32
  • 56
  • Possible duplicate of [Eval check for DBNull doesnt work](https://stackoverflow.com/questions/5224264/eval-check-for-dbnull-doesnt-work) – hardkoded Nov 17 '17 at 15:54
  • I've tried all of those solutions as well with the same error always. So this is different. This seems to be something more related with using the DataTable.Select method – abney317 Nov 17 '17 at 16:08

2 Answers2

1

CopyToDataTable should fix the issue:

LV_Employees.DataSource = employees.Select("Name LIKE '%" + TB_Search.Text + "%'")
    .CopyToDataTable();
LV_Employees.DataBind();
hardkoded
  • 18,915
  • 3
  • 52
  • 64
  • Perfect! Thanks! Didn't know about that method (clearly).. hadn't used the DataTable.Select stuff before. – abney317 Nov 17 '17 at 16:40
0

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"] = "";
}
abney317
  • 7,760
  • 6
  • 32
  • 56
  • Its not weird, DBNull can't be implicitly cast to string. It's the same problem you would have with anything that cannot be cast to string. Try `... (object)DBNull.Value ? ... ` – Crowcoder Nov 17 '17 at 16:22
  • `<%# Eval("Title") == (object)DBNull.Value ? "" : Eval("Title") %>` still gave the same error – abney317 Nov 17 '17 at 16:32