2013-10-08 46 views
4

如何檢查填充列表視圖的結果中是否存在列? 列表視圖從存儲過程中填充。檢查數據目錄中是否存在具有給定名稱的列

這是我試過,但沒有成功:

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

,或者我應該使用Ë代替的Container.DataItem

回答

10

首先,我會使用代碼隱藏,如果它變得複雜(我幾乎總是使用它)。在這裏,我將使用ListView的ItemDataBound event這是觸發每一個項目:

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"; 
     } 
    } 
} 

這使得代碼更可讀,可維護,可調試和類型安全。

1

您可以在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(); 
      } 
     } 
    } 

希望這會有所幫助!

+0

這是如何從[我的回答(http://stackoverflow.com/a/19247830/284240)公佈提前十分鐘不同? –

0

而且,我發現了一個解決方案:

public bool CheckProperty(string property_name) 
    { 

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

    } 
+2

不要使用'Try-Catch'作爲邏輯運算符。這是非常低效的。 –

+0

Try-Catch是否會影響性能? – POIR

+1

不是'Try-Catch'影響性能,但是可以有例外。而且由於你在這裏循環了很多有很多列的項目,所以它確實可能是性能至關重要的。但是,即使它不會損害表現,這也是一個不好的習慣。不,例外情況永遠不是正常流量控制的正確工具。例外只應用於表明由於外部原因,某個功能/方法無法履行合同。 –

相關問題