如何使用 C# 根据对象值查找行索引?

发布于 2024-11-15 15:37:09 字数 188 浏览 2 评论 0原文

我有一个 datagridview,我想从中删除特定行(datagridview 不是数据绑定)。要删除,我需要该行的索引。 Datagridview 项目都是对象。此时,我所拥有的只是对象的 id(属性)。我想知道 datagridview 中保存 id 对象的行的索引,比如 2。

我该如何完成这个?或者是否有另一种根据对象的值删除行的方法?

I have a datagridview, and I want to remove a particular row from it (datagridview is not data bound). To remove, I need the index of the row. Datagridview items are all objects. At this moment, all I have is the id (a property) of the object. I want to know the index of the row in datagridview which holds the object of id, say 2.

How do I accomplish this? Or is there another way of deleting a row based on an object's value?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

左秋 2024-11-22 15:37:09

可能有一种更简洁的方法,但使用 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();
}

和不使用 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");
}

There's 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");
}
痴梦一场 2024-11-22 15:37:09

如果您的 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);
}

这可以说是正确的方法,并且可能会给您带来更好的性能(您可能不需要)。然而,微软并没有让使用变得如此简单。框架 BindingList 对象不实现 FindCore,因此您需要创建自己的 IBindingList() (以及实现排序,因为您可能也需要这样做)。

下面是支持 Find() 的 IBindingList 实现的代码 (取自 MSDN)< /a>.

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;
}

如果您使用 DataTable 作为数据源,那么您将获得开箱即用的 Find() 行为,但既然您说您有一个自定义对象列表,那么您可能没有。

If your DataGridView's DataSource is a BindingSource and the underlying list implements FindCore then you can use the BindingSource Find() method like so:

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);
}

This is arguably the right way of doing it, and might give you better performance (which you probably won't need). However, Microsoft haven't made using this easy. The framework BindingList object does not implement FindCore so you will need to create your own IBindingList() (as well as implementing sorting, since you probably want that too).

Here is the code for an IBindingList implementation that supports Find() (taken from 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 are using a DataTable as your DataSource then you get the Find() behaviour out of the box, but since you say you have a list of custom objects, you probably aren't.

人间不值得 2024-11-22 15:37:09

类似 LINQ 的方法。

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 添加到他的答案中一样:)

快乐编码。

A LINQ'ish 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 :(
}

Here I use Rows.IndexOf -- otherwise the index could be worked into the LINQ query. There are a number of such examples on SO. (Like the one ICR added to his answer :)

Happy coding.

一枫情书 2024-11-22 15:37:09
var query = from DataGridViewRow row in _dataGrid.Rows 
            where  ((DataRowView)row.DataBoundItem).Row == boundedRow
            select row;

if (query.Count() > 0)
{
    // actions
}
var query = from DataGridViewRow row in _dataGrid.Rows 
            where  ((DataRowView)row.DataBoundItem).Row == boundedRow
            select row;

if (query.Count() > 0)
{
    // actions
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文