2

Hi I have DataGridView control that I manyally fill with items (no DataSource)

like that

        int row = dgvClients.Rows.Add();
        dgvClients.Rows[row].Cells["ClientObjectID"].Value = somevalue1;
        dgvClients.Rows[row].Cells["ClientCode"].Value = somevalue2;
        dgvClients.Rows[row].Tag = SomeObject1;

Pls note that each row in gridview represents some object and its Tag is set to specific object. Only one row can have Tag reference to one SomeObject. No duplicates.

Now I need to find datagridview ROW having reference to SomeObject. What is the best way?

Captain Comic
  • 15,744
  • 43
  • 110
  • 148
  • Let me clarify. I have some table and user can enter text to find items. I need to select the row that contains required text. I wonder if there is some "pattern". I don't want to do straight iteration and check – Captain Comic Nov 30 '09 at 19:08
  • So the searchable text is in Tag and not in the other columns? – John Nov 30 '09 at 19:11
  • Tag is reference to some class that have some properties (strings) datagridview columns represent all those properties and rows represents different instances of some class. User enters text and says which property (column) it is. I need to find right row and select it. – Captain Comic Nov 30 '09 at 19:16

2 Answers2

3

Here is something I put together that might do what you are describing. It is quick and dirty, but it might get you going:

I have a blank DataGridView, a combobox, and a textbox on a form. TestObject is a class that is an object with 3 string properties for testing purposes of this example.

For ease, I initialize a generic list with a few instances of TestObject. I then manually add 3 columns to the datagridview which correspond to the 3 properties of TestObject. I then iterate through the list and manually add them to the datagridview, as well as actually storing the object in the Row's tag property as well.

I then fill the combobox with references to the columns in the datagridview. The user will select which column she/he wants to search for, then type the text to match in the textbox.

I then handle the textbox textchanged event to search the datagridview based on the column that is selected in the combobox and the text in the textbox. For a bigger dataset, you wouldn't want to handle the textchanged event because it would be too slow to search after every letter change.

Without using a datatable or datasource, I can't think of any easy way to search the rows without iterating. I don't know your requirements, but I would use a bindingsource with a list or set up a datatable at a minimum. With a bindingsource you could also apply a filter and dynamically show only those results that match your search.

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            List<TestObject> objects = new List<TestObject>
                {
                        new TestObject("1", "object1", "first"),
                        new TestObject("2", "object2", "nada"),
                        new TestObject("3", "object3", "Hello World!"),
                        new TestObject("4", "object4", "last")
                };

            dataGridView1.Columns.Add("ColID", "ID");
            dataGridView1.Columns.Add("ColName", "Name");
            dataGridView1.Columns.Add("ColInfo", "Info");

            foreach (TestObject testObject in objects)
            {
                int row = dataGridView1.Rows.Add();
                dataGridView1.Rows[row].Cells["ColID"].Value = testObject.ID;
                dataGridView1.Rows[row].Cells["ColName"].Value = testObject.Name;
                dataGridView1.Rows[row].Cells["ColInfo"].Value = testObject.Info;
                dataGridView1.Rows[row].Tag = testObject;
            }

            foreach (DataGridViewColumn col in dataGridView1.Columns)
            {
                comboBox1.Items.Add(col);
            }

            comboBox1.ValueMember = "HeaderText";
            comboBox1.SelectedIndex = 0;
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            dataGridView1.ClearSelection();
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {

                if (row.Cells[((DataGridViewColumn)comboBox1.SelectedItem).Name].Value == null)
                {
                    continue;
                }
                if (row.Cells[((DataGridViewColumn)comboBox1.SelectedItem).Name].Value.ToString().Equals(
                        textBox1.Text,StringComparison.InvariantCultureIgnoreCase))
                {
                    row.Selected = true;
                    return;
                }
            }
        }
    }
}

public class TestObject
{
    public TestObject(string id, string name, string info)
    {
        ID = id;
        Name = name;
        Info = info;
    }

    public string ID { get; set; }
    public string Info { get; set; }
    public string Name { get; set; }
}
Jon Comtois
  • 1,824
  • 1
  • 22
  • 29
1

You could use LINQ and set the results as the datagridview datasource. This way all you would need to do is run the LINQ, bind it to the datagridview, and then refresh it.

In VB I would code it as so:

dim results = from obj in objects _
              where obj.<property> = <value> _
              select obj

datagridview1.datasource = results.tolist()
datagridview1.refresh()

If no one else comes up with a better answer I will create a test project this evening to give you practical C# code.

Wade

Wade73
  • 4,359
  • 3
  • 30
  • 46
  • Yes, LINQ is nothing more than extension methods. Look at this related post - http://stackoverflow.com/questions/2138/linq-on-the-net-2-0-runtime – Wade73 Apr 05 '10 at 12:23
  • It would be nice if you down vote my answer to add a comment to explain why. How will I improve without it? – Wade73 Dec 19 '12 at 14:16
  • I have a +1 on this answer as it provides a nice solution with latest versions of .net. Not sure where the -1 comes from... – Gad Jan 03 '13 at 15:06