'C# - Find a cell through a textBox in dataGridView

I've already searched for some solutions to my problem, but still didn't find anything working for me. So I signed up to get some help for my problem. Appreciate help.

public Form1()
{
    InitializeComponent();
    dataGridView1.Columns.Add("FirstNames", "FirstName");
    dataGridView1.Columns.Add("SecondNames", "SecondName");
    dataGridView1.Columns.Add("AccountNames", "AccountName");
    dataGridView1.Columns.Add("Emailaddresses", "Emailaddress");

    try
    {
        // enter AD settings  
        PrincipalContext AD = new PrincipalContext(ContextType.Domain, (ConfigurationManager.AppSettings["Domaene"]));

        using (var searcher = new PrincipalSearcher(new UserPrincipal(AD)))
        {
            foreach (var result in searcher.FindAll())
            {
                DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
                dataGridView1.Rows.Add
                (
                    de.Properties["givenName"].Value,
                    de.Properties["sn"].Value,
                    de.Properties["samAccountName"].Value,
                    de.Properties["userPrincipalname"].Value
                );                          
            }
        }
    }    
    catch (Exception ex)
    {
    }
}

This is the way how I create my ActiveDirectory and put it into my dataGridView. The function I am searching for is how to search through this DVG with a textBox. So I already tried something like this:

String searchValue = textBox1.Text;
int rowIndex = -1;

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (row.Cells[2].Value != null) // Need to check for null if new row is exposed
    {
        if (row.Cells[1].Value.ToString().Equals(searchValue))
        {
            rowIndex = row.Index;
            break;
        }
    }
}

This snippet is from another post of this site. I tried it on my build and it didn't work for me. It throws a System.NullReferenceException when I put something in my textBox. The problem: I really don't know why it doesn't work. Will appreciate any answer!

Greetings, MarvinR



Solution 1:[1]

Try this

    var dg = new DataGrid();
var tb = new TextBox();
tb.ID = "myTextBox"

foreach (DataGridItem item in dg.Items)
{
    foreach (var cell in item.Cells)
    {
        TextBox val = (TextBox)item.FindControl("textboxid here");
        if (val.Text == tb.Text)
        {
            //do something here
        }
    }
}

This will loop through each of the rows and the cellslooking for a value in a specific textbox, if you need to loop through other textboxes you could write another bit of code to look for all the controls in the data grid.

Solution 2:[2]

As a addition to what ivayle said you can also select the whole row if you will use the whole row's data later in your program:

        string searchValue = textBox1.Text;

        foreach (DataGridViewRow row in YourDataGridView.Rows)
        {
            foreach (DataGridViewCell cell in row.Cells)
            {
                try
                {
                if (cell.Value != null && cell.Value.ToString() == searchValue)
                {
                    //cell.RowIndex;
                    YourDataGridView.CurrentCell = YourDataGridView.Rows[cell.RowIndex].Cells[0];//selects only a cell of the row in which the value was found, in this case cell with index 0
                    YourDataGridView.CurrentRow.Selected = true;//selects the whole row of the current selected cell
                }
                }
                catch (Exception)
                {
                    MessageBox.Show("No records found.");
                    //throw;
                }
            }
        }
    

Solution 3:[3]

Introducing the power of LINQ

using System.Linq;

int GetRowID = YourDataGridView.Rows.Cast<DataGridViewRow>()
            .Select(s => (s.Cells["YourColumnWhereToFind"].Value != null) ? 
            (s.Cells["YourColumnWhereToFind"].Value.ToString() == textBox1.Text) 
            ? s.Index : -1 : -1).FirstOrDefault();

Just handle if returned -1 because I think you will get index out of bounds. (?)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Simon Price
Solution 2 Leonid-Stefanel Pintea
Solution 3 once ng kahirapan