Skip to main content
 首页 » 编程设计

c#之从 DataRow 内部的 DateTime 对象中提取数据

2024年02月23日18qq号

我有一个连接到存储培训类类(class)完成情况的 Oracle 数据库的小应用程序。该数据库包含员工姓名、员工编号、类(class)完成日期和类(class)名称。我有返回一行的代码,如下所示:

            String strPerIdNo = textBox1.Text; 
            String strQuery = "PER_ID_NO = " + "'" + strPerIdNo + "'"; 
            DataRow[] foundRows; 
            foundRows = dataSet1.DataTable1.Select(strQuery); 

该行包含 5 个元素的数组:

  • [0] - System.DateTime 对象
  • [1] - 字符串对象
  • [2] - 整数对象
  • [3] - 字符串对象
  • [4] - 字符串对象

我想从 [0] 数组中的 DateTime 对象实例化一个 DateTime 对象,但我不知道如何做。我想显示一条消息,其中包含员工姓名和他们完成类(class)的日期。

谢谢!

请您参考如下方法:

好的,首先,您没有在这里实例化任何东西,因为您想要的 DateTime 已经存在(否则,它不会在 DataRow 中!)。另外,DateTime是值类型,不是引用类型;想到实例化一个值类型是不正常的;您只需初始化或复制它们。

您正在寻找的是获取 DataRow 中 DateTime 元素的值。以下是步骤:

//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;