Search code examples
c#wpfdatatabledatagrid

How to get cell value after clicking on datagrid row


I have a C# WPF DataGrid to list information about documents (e.g. invoices). The user is able to select one row in the Datagrid. After double-clicking the row I need to access a specific cell value (docId).

Unfortunately I don't know how to access the correct datarow behind the selected datagrid row.

I can access following values from my grid:

dataGrid_docs.selectedValue
dataGrid_docs.selectedItem

...

selected Value is not the answer to my problem because the user ist clicking any row, not always the correct column.

        // Create a new DataTable.    
        DataTable custTable = new DataTable("Customers");


        // Create docId column 
            dtColumn = new DataColumn();
            dtColumn.DataType = typeof(string);
            dtColumn.ColumnName = "docId";
            custTable.Columns.Add(dtColumn);

        // Create createDate column 
            dtColumn = new DataColumn();
            dtColumn.DataType = typeof(string);
            dtColumn.ColumnName = "createDate";
            custTable.Columns.Add(dtColumn);


        dtSet = new DataSet();
        dtSet.Tables.Add(custTable);



        foreach (var doc in docs)
        {
            myDataRow = custTable.NewRow();
            foreach (var attribute in ecoDmsAttributes)
            {                    
                myDataRow["docId"] = "123"
                myDataRow["createDate"] = "2019-08-27"
            }
            custTable.Rows.Add(myDataRow);
        }


        dataGrid_docs.ItemsSource = custTable.DefaultView;




    private void DataGrid_docs_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        DataRowView docid = dataGrid_docs.SelectedItem;

        txt_Debug.Text = "Clicked on docId: " + docid.ToString();
    }

Solution

  • you can retrive values from DataRowView by column name, e.g. dataRowView["docId"]

    private void DataGrid_docs_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        DataRowView dataRowView = (DataRowView)dataGrid_docs.SelectedItem;
    
        txt_Debug.Text = "Clicked on docId: " + dataRowView["docId"];
    }