MarvinR
MarvinR

Reputation: 13

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

Upvotes: 0

Views: 2598

Answers (4)

bakit ko pinasok to
bakit ko pinasok to

Reputation: 61

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. (?)

Upvotes: 0

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

Upvotes: 0

ivayle
ivayle

Reputation: 1070

Basically you would like to enumerate through all cells and once you find the value you are searching for to return the row index of this cell. Therefore your code should be as non-prompt to null reference exceptions as it could be. An example of such a method.

private int SearchValueRowIndex()
{
    string searchValue = textBox1.Text;

    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        foreach (DataGridViewCell cell in row.Cells)
        {
            if (cell.Value != null && cell.Value.ToString() == searchValue)
            {
                return cell.RowIndex;
            }
        }
    }

    // Not found
    return -1;
}

Upvotes: 2

Simon Price
Simon Price

Reputation: 3271

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.

Upvotes: 0

Related Questions