2010-01-06 130 views
0

的细胞文本我需要从SQL表中获取日期时间,但我有两个问题:Reffering从WPF的DataGrid

  1. 我需要从DataGrid中的选定单元格是指串。我试过“bksDataGrid.CurrentCell.Item”,但这不起作用。
  2. 不是真的有问题,但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); 
    

对不起,最终的语法错误。

回答

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“对象物obj =新的对象() ;”不需要;

b.you可以将cmd.ExecuteScalar的结果转换为DateTime。在投射之前,你也想检查它不是null或DBNull;否则您可能会收到“指定的演员无效”例外。

希望这会有所帮助,关注