How to find row index based on object value using C #?

I have a datagridview and I want to remove a specific row from it (datagridview is not data bound). To delete, I need a row index. Datagridview elements are all objects. At this point, all I have is the id (property) of the object. I want to know the row index in a datagridview that contains an id object, say 2.

How to do it? Or is there another way to delete a row based on the value of an object?

+3
source share
4 answers

Probably a cleaner way, but with LINQ:

private int GetIndexOfRowWithId(DataGridView dataGrid, int id) {
    return dataGrid.Rows.Cast<MyRowObj>().Select((row, index) => new {
        index,
        row
    }).Where(x => x.row.id == id).Select(x => x.index).First();
}

and without LINQ:

private int GetIndexOfRowWithId(DataGridView dataGrid, int id) {
    for (int i = 0; i < dataGrid.Rows.Count; i += 1) {
        MyRowObj row = (MyRowObj)dataGrid.Rows[i].Tag; // or.DataBoundItem;
        if (row.id == id) {
            return i;
        }
    }

    throw new ArgumentException("No item with specified id exists in the dataGrid.", "id");
}
+3
source

LINEAR approach.

var row = dataGrid.Rows.OfType<MyRowObj>().FirstOrDefault(r => r.id == id);
if (row != null) {
   var rowIndex = dataGrid.Rows.IndexOf(row);
   // ... if you need the row index
} else {
   // cry :(
}

Rows.IndexOf - LINQ. SO . ( ICR, :)

.

+1

DataGridView DataSource BindingSource, FindCore, BindingSource Find() :

BindingList<YourObject> objectList = new BindingList<YourObject>();
BindingSource source = new BindingSource();
source.DataSource = objectList;

dataGridView1.DataSource = source;

private int GetIndexOfItemById(int id)
{
    return source.Find("Id", id);
}

, , ( , , ). , Microsoft . Framework BindingList FindCore, IBindingList() ( , , , ).

IBindingList, Find() ( MSDN).

protected override bool SupportsSearchingCore
{
    get
    {
        return true;
    }
}

protected override int FindCore(PropertyDescriptor prop, object key)
{
    // Get the property info for the specified property.
    PropertyInfo propInfo = typeof(T).GetProperty(prop.Name);
    T item;

    if (key != null)
    {
        // Loop through the items to see if the key
        // value matches the property value.
        for (int i = 0; i < Count; ++i)
        {
            item = (T)Items[i];
            if (propInfo.GetValue(item, null).Equals(key))
                return i;
        }
    }
    return -1;
}

If you use a DataTable as your DataSource, you get the Find () behavior out of the box, but since you say you have a list of user objects, you probably don't know.

+1
source
var query = from DataGridViewRow row in _dataGrid.Rows 
            where  ((DataRowView)row.DataBoundItem).Row == boundedRow
            select row;

if (query.Count() > 0)
{
    // actions
}
0
source

All Articles