Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a column with a given name exists in a datarow

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 ?

like image 386
POIR Avatar asked Oct 08 '13 12:10

POIR


2 Answers

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.

like image 106
Tim Schmelter Avatar answered Sep 18 '22 10:09

Tim Schmelter


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!

like image 31
Abhishek Shukla Avatar answered Sep 20 '22 10:09

Abhishek Shukla