Tutorial :Reffering to text from cell of WPF DataGrid


I need to get datetime from SQL table but I have two problems:

  1. I need to refer to string from selected cell of DataGrid. I've tried "bksDataGrid.CurrentCell.Item" but that doesn't work.
  2. Not really problem, but the cmd will return SQL datetime as object. Is it possible to convert it to .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);  

Sorry, for eventual grammar mistakes.


For #1 you can do following:

foreach (DataGridCellInfo cellInfo in dataGrid.SelectedCells)  {      DataGridCell gridCell = TryToFindGridCell(dataGrid, cellInfo);      if (gridCell != null && gridCell.Content is TextBlock)          Console.WriteLine(((TextBlock)gridCell.Content).Text);  }  

below is TryToFindGridCell procedure implementation:

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


a.line "object obj = new object();" is not needed;

b.you can cast the result of cmd.ExecuteScalar to DateTime. You also would want to check it's not null or DBNull before casting; otherwise you can get a "Specified Cast is Not Valid" exception.

hope this helps, regards

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »