unnamed
unnamed

Reputation: 856

How to get Column Value of a DataRow in a Datatable

I have a DataTable which is bind to dataGridview in my code.

When I get datas from database, the gridview works fine. it fills with data. What I want to do is getting the primary key value of the specified row.

Ex:

PK         Address          Phone
1          xxxyyyzzz...     1234567   
2          aaabbbccc...     2345678

What I want is this. User will click on any row, then click on a button to add some stuff. Then I will get PK value, and do other stuffs.

How can I do it?

Upvotes: 1

Views: 12256

Answers (2)

SventoryMang
SventoryMang

Reputation: 10479

Hmm can you specify how and when you are talking about getting this value?

You can do this:

int index = dt.Rows.IndexOf(row);

But I am not sure what the point of that would be, if you already have the specified row, why can't you just get the PK via row[columnName]?

But this is more resource intensive than just looping through with a for loop.

Do you need this before or after binding to the dataGridView? If you need to get the value from the dataGridView row that is different.

For your edit:

You would can get the selected row like so:

if (yourDataViewGrid.SelectedRows.Count == 1) 
{ 
Int pk = yourDataViewGrid.Rows[yourDataViewGrid.SelectedRows[0].Index].Cells["PK"].Value.ToString(); 
} 

If you are doing it by some other method like using a checkbox to select a row, you would do this:

foreach (DataGridViewRow row in YourDataGridView.Rows)
        {

            if ((Boolean)((DataGridViewCheckBoxCell)row.Cells["CheckBoxName"]).FormattedValue)
            {
               Int pk = rows.Cells["PK"].Value.ToString();
            }

        }

Upvotes: 3

Kleinux
Kleinux

Reputation: 1541

The DataGridView control binds to a DataTable using the DataView class. You can use something like this to get the DataRow of a DataGridViewRow

var vrow = (DataRowView)grid.Rows[12].DataBoundItem; // get the bound object
var drow = vrow.Row; // the Row property references the real DataRow

where 12 is the index you are looking for. Sometimes it helps to set the DataSource property to a DataView explicitly and keep a reference to it on your form. The view will know the sorting of the data too

var view = new DataView(table);
grid.DataSource = view;

Upvotes: 2

Related Questions