ale
ale

Reputation: 3421

DataGrid to DataRowView

I need charged the item value from a dataGrid when user click on, into a datarowview to take the first value "IdEmployee" and assign to a variable.

This is my method, the problem is my variable dataRowView is Null!

How can I fix this?

private void _employeedataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    DataRowView dataRowView = _employeedataGrid.CurrentCell.Item as DataRowView;
    var idEmployee = Convert.ToInt32(dataRowView.Row[0]);

    .......
} 

Upvotes: 3

Views: 9111

Answers (4)

A. Lartey
A. Lartey

Reputation: 57

As long as the item is selected, you can get the values for each column directly without going through a loop. Column 1 will have an index Row.ItemArray[0], column 2 will have an index Row.ItemArray[1] etc. It all depends on your mission.

var EmpID = Convert.ToInt32(((DataRowView)_employeedataGrid.SelectedItem).Row.ItemArray[0].ToString());

Upvotes: 0

Prashant Manjule
Prashant Manjule

Reputation: 312

            //during datagrid events like RowEditEnding, SelectionChange event 'e' will be very useful as...
            DataGridRow row1 = e.Row;
            int row_index = ((DataGrid)sender).ItemContainerGenerator.IndexFromContainer(row1);

            //or try this if works
            int i_row = e.Row.GetIndex();

Upvotes: 0

mohammad jannesary
mohammad jannesary

Reputation: 1821

That's what you need

DataRowView view = _employeedataGrid.Items[_employeedataGrid.SelectedIndex] as DataRowView;

Upvotes: 2

Ethan Cabiac
Ethan Cabiac

Reputation: 4993

That is because _employeedataGrid.CurrentCell.Item cannot be cast as a DataRowView. Why don't you try CurrentRow instead of CurrentCell?:

private void _employeedataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    DataRowView dataRowView = _employeedataGrid.CurrentRow.Item as DataRowView;
    var idEmployee = Convert.ToInt32(dataRowView.Row[0]);
    .......
} 

Upvotes: 2

Related Questions