Pergunta

I am having trouble trying to figure on how to hide a ',' when the DataItem is empty.

Basically, I have table row that displays Registered Address and populated using the following technique:

<%# DataBinder.Eval(Container.DataItem, "Address_Line_1" )%>,
<%# DataBinder.Eval(Container.DataItem, "Address_Line_2")%>,
<%# DataBinder.Eval(Container.DataItem, "TOWNLAND")%>,                          
<%# DataBinder.Eval(Container.DataItem, "CITY")%>,
<%# DataBinder.Eval(Container.DataItem, "STATE")%>,

Now if one or many of the above DataItem comes back as Empty then on the front end it is displayed as

Address 1, , , CITY, ,

I tried the following to hide the comma (',') but I keep getting an error saying

Missing ')' on the first line of 'If' statement

<%#IIf(IsDBNull(DataBinder.Eval(Container.DataItem, "STATE")) OrElse 

String.IsNullOrEmpty(DataBinder.Eval(Container.DataItem, "STATE")) , "" , 

DataBinder.Eval(Container.DataItem, "STATE") & ",")%>

I am not sure whether my 'if' statement is wrong or It can't be done as above?

Anybody have suggestions about the above or any other alternative way of hiding the comma if a NULL value?

Foi útil?

Solução

This should work:

<%# DataBinder.Eval(Container.DataItem, "Address_Line_1") != null && !String.IsNullOrEmpty(DataBinder.Eval(Container.DataItem, "Address_Line_1").ToString()) ? DataBinder.Eval(Container.DataItem, "Address_Line_1").ToString() + "," : "" %>

condition ? true : false

Outras dicas

You can call methods in code-behind so you can take this logic out of your markup, like this:

protected string GetAddress()
{
    string boundAddressValue = Eval("Address_Line_1") as string;

    return !String.IsNullOrEmpty(boundAddressValue) ? boundAddressValue : String.Empty;
}

Now you can call it via markup like this:

<%# GetAddress() %>

Note: The downside to this approach is that if you call GetAddress outside of data-binding, then Eval will blow up, but it makes your markup much cleaner and you gain the help of the editor to help with syntax issues.

just Use

(DataBinder.Eval(e.Row.DataItem, "ColumnName") ?? "AnyValueAccordingToColumnDataTyle")

a bit late, but how about something like

protected string GetAddress()
{
    var parts = new List<string>(new string[] 
    {
         Eval("Address_Line_1") as string,
         Eval("Address_Line_2") as string,
         Eval("TOWNLAND") as string,                          
         Eval("CITY") as string,
         Eval("STATE") as string
    });

    return string.Join(", ", parts.Where(x => !string.IsNullOrEmpty(x)).ToArray());
}

// or

protected string JoinEval(string delim, param string[] fields)
{
    var parts = new List<string>();
    foreach (string field in fields)
    {
         string value = Eval(field).ToString();
         if (!string.IsNullOrEmpty(value))
              parts.Add(value);
    }

    return string.Join(delim, parts.ToArray());
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top