C# 检查数据行中是否存在具有给定名称的列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19247384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a column with a given name exists in a datarow
提问by Ptheitroad
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 einstead Container.DataItem?
还是应该使用e代替Container.DataItem?
回答by Tim Schmelter
First, i would use codebehind if it's getting complicated (i use it almost always). Here i would use the ListView's ItemDataBound
eventwhich is triggered for every item:
首先,如果它变得复杂,我会使用代码隐藏(我几乎总是使用它)。在这里,我将使用为每个项目触发的 ListViewItemDataBound
事件:
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.
这使得代码更具可读性、可维护性、可调试性和类型安全性。
回答by Abhishek Shukla
You can check this in OnItemDataBound.
您可以在 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!
希望这可以帮助!
回答by Ptheitroad
Also, I found a solution:
另外,我找到了一个解决方案:
public bool CheckProperty(string property_name)
{
try
{
Eval(property_name);
}
catch { return false; }
return true;
}