如何以编程方式设置标签文本 - Linq To Entities
我必须根据用户偏好在网页上设置大量不同标签的标签文本。
我在标签加载事件上放置了以下代码(可能是错误的!)
string memberid = Session["MemberID"].ToString();
string locationid = Session["LocationID"].ToString();
string userName = Membership.GetUser().UserName;
string uuf1 = "UnitUserField1";
MyEntities lblUUF1Text = new MyEntities();
lblUUF1.Text = lblUUF1Text.tblUserPreferences
.Where(p => p.MemberID == memberid && p.LocationID == locationid && p.Username == userName && p.ColumnName == uuf1)
.Select(p => p.Alias)
.ToString();
但是,当我运行此代码时,返回的标签文本是:
System.Data.Objects.ObjectQuery`1[System.String]
有人可以在我的方法错误。我现在感觉非常非常厚重。
I have to set the label text of a load of differnet labels on a web page based upon user preferences.
I have the following code that is place upon the label load event (probably wrong!)
string memberid = Session["MemberID"].ToString();
string locationid = Session["LocationID"].ToString();
string userName = Membership.GetUser().UserName;
string uuf1 = "UnitUserField1";
MyEntities lblUUF1Text = new MyEntities();
lblUUF1.Text = lblUUF1Text.tblUserPreferences
.Where(p => p.MemberID == memberid && p.LocationID == locationid && p.Username == userName && p.ColumnName == uuf1)
.Select(p => p.Alias)
.ToString();
However when I run this, the label text returned is:
System.Data.Objects.ObjectQuery`1[System.String]
Can someone point me in the error of my ways. I'm feeling very, very thick at the moment.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在编写一个查询,然后要求将该查询转换为字符串。您只想要该查询的第一个结果吗?如果是这样,那就很简单了:(
我假设
p.Alias
的类型已经是string
,但是您包含了对ToString
的调用> 作为尝试将查询强制转换为字符串以使其编译。)请注意,如果没有结果,则会出现异常。否则它将采用第一个结果。其他选项包括:
Single()
SingleOrDefault()
,存储在局部变量中,如果结果不为 null,则设置标签文本。FirstOrDefault()
。You're writing a query and then asking that query to be converted to a string. Do you only want the first result of that query? If so, it's easy:
(I'm assuming that the type of
p.Alias
is alreadystring
, but that you included the call toToString
as an attempt to coerce the query into a string to make it compile.)Note that if there are no results, that will blow up with an exception. Otherwise it'll take the first result. Other options are:
Single()
SingleOrDefault()
, store in a local variable and set the label text if the result isn't null.FirstOrDefault()
in the same way.你需要一个
.First()
在那里You need a
.First()
in thereToString() 将返回您所看到的对象类型,您需要做的是:
ToString() will return the object type as you see, what you will need to do is this: