1

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;

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. It would be nice to know how to get the other values as well.

David Pfeffer
  • 38,869
  • 30
  • 127
  • 202
user1007103
  • 405
  • 6
  • 11
  • 16
  • 1
    As your controls have the runat=server set, can't you just assign the values to the label in the code behind and set the formatting accordingly? – Kev Ritchie Dec 19 '11 at 13:33

2 Answers2

3

You may use DataTable methods to read values directly from the table object.

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.

DataRow[] rows = table.Select("column1='value1'");
abatishchev
  • 98,240
  • 88
  • 296
  • 433
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
2

Yes, you can directly investigate the data held in the DataTable.

DataTable can be made into an IEnumerable, and can be queried. 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.

Community
  • 1
  • 1
David Pfeffer
  • 38,869
  • 30
  • 127
  • 202