Pulling data out from a DateTime object that is inside of a DataRow?
I have a little app that connects to an Oracle database that stores course completions for a training class. The database has employee names, employee numbers, date the course was completed, and the name of the course. I have code that returns one row, shown below:
String strPerIdNo = textBox1.Text;
String strQuery = "PER_ID_NO = " + "'" + s开发者_运维知识库trPerIdNo + "'";
DataRow[] foundRows;
foundRows = dataSet1.DataTable1.Select(strQuery);
The row contains an array of 5 elements:
- [0] - System.DateTime object
- [1] - String object
- [2] - Int object
- [3] - String object
- [4] - String object
I want to instantiate a DateTime object from the DateTime object in the array at [0], but I cannot figure out how. I want to display a message that contains the emp name and date they completed the course.
Thank you!
Okay, first, you're not instantiating anything here, because the DateTime you want already exists (or else, it wouldn't be in the DataRow!). In addition, DateTime is a value type, not a reference type; it's not normal to think of instantiating a value type; you just initialize or copy them.
What you are looking for is to get the value of the DateTime element in your DataRow. Here are the steps:
//step 0: make sure there's at least one DataRow in your results
if (foundRows.Length < 1) { /* handle it */ }
//step 1: get the first DataRow in your results, since you're sure there's one
DataRow row = foundRows[0];
//step 2: get the DateTime out of there
object possibleDate = row["TheNameOfTheDateColumn"];
//step 3: deal with what happens if it's null in the database
if (possibleDate == DBNull.Value) { /* handle it */ }
//step 4: possibleDate isn't a DateTime - let's turn it into one.
DateTime date = (DateTime)possibleDate;
If it's a DateTime object then why not just cast it? Like
foreach(DataRow row in foundRows) { var dt = (DateTime)row[0]; }
精彩评论