我需要从SQL表中获取日期时间,但我有两个问题:
不是真的有问题,但cmd会将SQL datetime作为对象返回。是否可以将其转换为.NET DateTime?
object obj = new object();
using (SqlConnection conn=new SqlConnection (SQLLogic.ConnString1))
{
conn.Open();
SqlCommand cmd = new SqlCommand(String.Format("SELECT ReturnDate FROM Borrows WHERE Name='{0}'",bksDataGrid.CurrentCell.Item, conn),conn);
obj = cmd.ExecuteScalar();
conn.Close();
}
obj = Convert.ToDateTime(obj);
抱歉,最终出现语法错误。
答案 0 :(得分:1)
对于#1,您可以执行以下操作:
foreach (DataGridCellInfo cellInfo in dataGrid.SelectedCells)
{
DataGridCell gridCell = TryToFindGridCell(dataGrid, cellInfo);
if (gridCell != null && gridCell.Content is TextBlock)
Console.WriteLine(((TextBlock)gridCell.Content).Text);
}
下面是TryToFindGridCell程序实现:
static DataGridCell TryToFindGridCell(DataGrid grid, DataGridCellInfo cellInfo)
{
DataGridCell result = null;
DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(cellInfo.Item);
if (row != null)
{
int columnIndex = grid.Columns.IndexOf(cellInfo.Column);
if (columnIndex > -1)
{
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);
result = presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex) as DataGridCell;
}
}
return result;
}
static T GetVisualChild<T>(Visual parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null) child = GetVisualChild<T>(v);
if (child != null) break;
}
return child;
}
#2:
a.line“object obj = new object();”不需要;
b。您可以将cmd.ExecuteScalar的结果强制转换为DateTime。您还希望在转换之前检查它是否为null或DBNull;否则你可以获得“指定的演员无效”例外。
希望这有帮助,尊重