正如 Dan 和 Hogan 正确指出的那样,
由于数据类型不匹配,您会收到错误消息。
SqlReader可以为您提供各种格式的数据,请参考
https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqldatareader?view=dotnet-plat-ext-5.0
对于所有可用的选项,
回到您的问题,我们的要求是从 Sqlserver 数据库中仅提取 Date 列并将其显示在文本框或列表框中
向 SqlReader 请求正确的数据类型
既然我们的需求是读取Date,我们就使用SqlDataReader.GetDateTime()
rdr.GetDateTime(8); //if you prefer index
或
rdr.GetDateTime("last_update"); //if you prefer column name
提取所需信息
rdr.GetDateTime(8) 将获取我们一个 DateTime 对象,因为我们对事物的 Date 部分感兴趣,让我们使用 .Date 属性提取此实例的 Date 组件
我们的代码现在将变成
rdr.GetDateTime(8).Date;
转换为所需格式
由于我们希望在某些控件中显示它,例如文本框或列表项,它需要一个字符串,现在让我们使用 .ToString() 将提取的 Date 转换为字符串
rdr.GetDateTime(8).Date.ToString(""); //gives time 12:00:00 AM with date as default
将日期格式化为选择的格式
我们可以使用各种可用的日期格式进一步格式化日期
参考https://docs.microsoft.com/en-us/dotnet/api/system.datetime.date?view=net-5.0
对于您的问题,我们可以使用日期短字符串格式
rdr.GetDateTime(8).Date.ToString("d");//gives just the Date Part
将值分配给控件
如果文本框
txtBoxName.Text = rdr.GetDateTime(8).Date.ToString("d");
如果是列表框
lstContacten.Items.Add(rdr.GetDateTime(8).ToDate().ToString());