views:

2169

answers:

2

Hi,

I want to retrieve the grid view row based on the cell value. For example, I am having a grid view with 4 columns (name,m1,m2,m3) and name contains unique values. So, I want to get the grid view row corresponding to the name specified.

Thanks

A: 

EDIT: I realized you probably meant the ASP.NET GridView not the WinForm DataGridView, which is what I originally answered for. The approach is very different in that case.

Just in case I left the WinForm DataGridView approach below.

ASP.NET GridView

The GridView is somewhat annoying in that it doesn't allow you to access cells by column name. Instead you need to know the index. You could hardcode it, but that's not desirable.

Hardcoded approach:

string searchValue = "SpecifiedName";
// where 1 is the hardcoded cell index
var query = from GridViewRow row in GridView1.Rows
            where row.Cells[1].Text == searchValue
            select row;
GridViewRow result = query.FirstOrDefault();

Dynamic Approach (Column Index Lookup):

string colName = "name";
int index = (from DataControlField col in GridView1.Columns
            where col.HeaderText == colName
            select GridView1.Columns.IndexOf(col)).FirstOrDefault();

// index used
var query = from GridViewRow row in GridView1.Rows
        where row.Cells[index].Text == searchValue
        select row;
GridViewRow result = query.FirstOrDefault();

Alternate index lookup: instead of using HeaderText you can use BoundField.

int index = (from DataControlField col in GridView1.Columns
            where ((BoundField)col).DataField == colName
            select GridView1.Columns.IndexOf(col)).FirstOrDefault();

WinForm DataGridView

Kept this here just in case.

string name = "SpecifiedName";
var query = from DataGridViewRow row in dataGridView1.Rows
            where row.Cells["name"].Value.ToString() == name
            select row;
// the row will be returned by this or contain a default value if not found
DataGridViewRow result = query.FirstOrDefault();
Ahmad Mageed
+1  A: 

This is what the DataKey property is used for. So: GridView1.DataKeyNames="name"

And to find your match:

   foreach (GridViewRow gvr in GridView1.Rows)
    {
        if (GridView1.DataKeys[gvr.RowIndex].ToString().Equals("mymatch"))
        {
            GridView1.SelectedIndex = gvr.RowIndex;
            break;
        }
    }

More code then needed to do this, but you get the idea. Now you don't need to show the "name" column if you don't want to.

JBrooks