参考WPF DataGrid单元格中的文本

时间:2010-01-06 19:03:12

标签: c# .net sql wpf datetime

我需要从SQL表中获取日期时间,但我有两个问题:

  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);
    
  3. 抱歉,最终出现语法错误。

1 个答案:

答案 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;否则你可以获得“指定的演员无效”例外。

希望这有帮助,尊重