Search code examples
c#messagebox

How to display searched rows in messagebox


can you please help me on displaying the searched row in message box?

I've below code for searching a value in the row.

private void button3_Click(object sender, EventArgs e)
{
        // Code to search the  alphanumneric Part Number (in Column1 header called "Name") and highlihgt the row

    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if (row.Cells["Age"].Value.ToString().Equals(textBox3.Text.StringComparison.CurrentCultureIgnoreCase))   
        {  
            dataGridView1.Rows[row.Index].Selected = true;
        }
    }
}

Solution

  • If what you are trying to do is display the Name column's value in a MessageBox then do the following:

    private void button3_Click(object sender, EventArgs e)
    {
        // Code to search the  alphanumneric Part Number (in Column1 header called "Name") and highlihgt the row
    
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.Cells["Age"].Value.ToString().Equals(textBox3.Text.StringComparison.CurrentCultureIgnoreCase))   
            {  
                dataGridView1.Rows[row.Index].Selected = true;
                MessageBox.Show(row.Cells["name"].Value.ToString());
                break;  //This exits the `foreach` loop - not necessary just an assumption.
            }
            else
            {
                //Do something if you don't find what you wanted or `continue` if you want the loop to keep going.
            }
        }
    }