8

How can I check if a column exists in result that populate a listview? The listview is populated from a stored procedure.

This is what I tried but no success:

<%#  Container.DataItem.GetType().GetProperty("Phone")==null?"phone is null":"we have phone property" #>

or should I use e instead Container.DataItem ?

POIR
  • 3,110
  • 9
  • 32
  • 48

3 Answers3

15

First, i would use codebehind if it's getting complicated (i use it almost always). Here i would use the ListView's ItemDataBound event which is triggered for every item:

protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    if (e.Item.ItemType == ListViewItemType.DataItem)
    {
        // assuming you have an ItemTemplate with a label where you want to show this
        Label lblInfo = (Label) e.Item.FindControl("LblInfo");
        DataRowView rowView = (DataRowView)e.Item.DataItem;
        if (rowView.Row.Table.Columns.Contains("Phone"))
        {
            lblInfo.Text = "we have the phone property";
        }
        else
        {
            lblInfo.Text = "no phone available";
        }
    }
}

That makes the code much more readable, maintainable, debuggable and type safe.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
3

You can check this in OnItemDataBound.

 protected void lstSample_OnItemDataBound(object sender, ListViewItemEventArgs e)
    {
        Label lblText = null;
        Boolean isColumnExists = false;
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            DataRowView dr = (DataRowView)e.Item.DataItem;
            isColumnExists  = dr.DataView.Table.Columns.Contains("Hello");
            lblText = (Label)e.Item.FindControl("lbltext");
            if (isColumnExists)
            {

                lblText.Text = dr.Row["Hello"].ToString();
            }
            else
            {
                lblText.Text = dr.Row["Movies"].ToString();
            }
        }
    }

Hope this helps!

Abhishek Shukla
  • 646
  • 1
  • 8
  • 21
0

Also, I found a solution:

    public bool CheckProperty(string property_name)
    {

        try
        {
            Eval(property_name);
        }
        catch { return false; }
        return true;

    }
POIR
  • 3,110
  • 9
  • 32
  • 48
  • 2
    Don't use `Try-Catch` as logical operator. This is very inefficient. – Tim Schmelter Oct 08 '13 at 14:01
  • 1
    Not the `Try-Catch` affects performance but an exception can. And since you're looping probably many items with several columns here it could indeed be performance critical. However, even if it doesn't hurt performance it's a bad habit to kick. No, exceptions are never the right tool for normal flow control. Exceptions should only be used to indicate that a function/method can't fulfil its contract due to external reasons. – Tim Schmelter Oct 08 '13 at 14:21