简体   繁体   English

从DataTable获取值而不将数据绑定到UI控件?

[英]Get values from DataTable without data binding to UI controls?

I always get values from the database directly to a control like this: 我总是直接从数据库中获取值到这样的控件:

Code-behind: 后台代码:

DataTable table = GetUserInfo();

UserInfo.DataSource = table;
UserInfo.DataBind();

string FirstName = lblFirstName.Text;
string LastName = lblLastName.Text;
DateTime BecomeAMember = DateTime.Parse(lblBecomeAMember.Text);

Markup: 标记:

<asp:Label ID="lblCity" runat="server" Text='<%# Eval("FirstName") %>' />
<asp:Label ID="lblLastName" runat="server" Text='<%# Eval("LastName") %>' />
<asp:Label ID="lblBecomeAMember" runat="server" Text='<%# Eval("BecomeAMember", "{0:dd MMM yyy) %>' />

There has to be a way to use the data in code-behind without putting it to a label and then use String text = label.Text; 必须有一种方法可以在代码隐藏的情况下使用数据而不将其放入标签,然后使用String text = label.Text;

I need the minutes and hours from BecomeAMember , and I don't want to use another Label with the full DateTime and make it invisible. 我需要距离BecomeAMember的分钟和小时,并且我不想使用带有完整DateTime另一个Label并使它不可见。 It would be nice to know how to get the other values as well. 很高兴知道如何获取其他值。

You may use DataTable methods to read values directly from the table object. 您可以使用DataTable方法直接从table对象读取值。

For instance, 例如,

string firstName = table.Rows[0]["FirstName"].ToString();

or 要么

foreach (DataRow row in table.Rows)
{
    //
}

Or use Select() method to search on specified field. 或使用Select()方法搜索指定的字段。

DataRow[] rows = table.Select("column1='value1'");

Yes, you can directly investigate the data held in the DataTable . 是的,您可以直接调查DataTable保存的DataTable

DataTable can be made into an IEnumerable , and can be queried. 可以将DataTable制成IEnumerable ,并可以进行查询。 In your case: 在您的情况下:

var datetimes = table.AsEnumerable().Select(x => x.Field<DateTime>("BecomeAMember"));

If you really only expect a single row, you can do either: 如果您确实只期望一行,则可以执行以下任一操作:

var dt = table.AsEnumerable().Select(x => x.Field<DateTime>("BecomeAMember")).Single();

or: 要么:

var dt = (DateTime) table.Rows[0]["BecomeAMember"];

Then format dt using ToString with a format string. 然后使用ToString和格式字符串格式化dt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM