I am going to try to make it very short and sweet. I have seen how to do this with a datagridview but I can't seem to find it with a normal datagrid. I have a SelectedCellsChanged event that fires off that I want to get a field in a column at the selected row. So when they select an enite row I want to pull the truckercode field so I can do a SQL query on the truckercode cell of that row. I am not doing a Binding for my datagrid. My code for how I fill my data grid is
using (SqlConnection connection = new SqlConnection("server=Server; database=db; user id=user; password=user"))
{
connection.Open();
using (SqlCommand command = new SqlCommand("SELECT * FROM SOMETABLE JOIN OTHERTABLE ON SOMETABLE.TRUCKERCODE = OTHERTABLE.TRUCKERCODE WHERE SOMETABLE.ACTIVE = 1 AND OTHERTABLE.ACTIVE = 1", connection))
{
SqlDataAdapter reader = new SqlDataAdapter(command);
DataSet dataSet = new DataSet();
reader.Fill(dataSet);
FirstGrid.ItemsSource = dataSet.Tables[0].DefaultView;
}
connection.Close();
connection.Dispose();
}
I think based on DataGrid Get Selected I think my code should look similar to
private void FirstGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
DataGrid grid = sender as DataGrid;
DataRowView row = grid.SelectedItems as DataRowView;
MessageBox.Show("" + grid.SelectedItems.Count);
if (grid.SelectedItems.Count > 0)
{
MessageBox.Show(row["TruckerCode"].ToString());
}
}
But I get a Argument out of range exception.
Another helpful post is Looping Through A DataView
I Solved my own problem. I hope anyone that reads this in the future that wants to get a value from selected columns from an entire selected row would use this. This example would print each cell for however many rows they have selected.
var grid = FirstGrid.SelectedItems;
foreach(DataRowView row in grid)
{
if (grid.Count == 1)
{
MessageBox.Show(row["NameOfTheColumn"].ToString());
}
}
If you add the grid.Count == 1 it prevents multiple rows from firing off your code. So you only have 1 row in the DataRowView otherwise you may have multiple DataRowViews.