Start New Discussion within our Software Development Community

How can I loop through a particular column of a datagridview? For example, I have three tables and I only need to get the selected items of the first column. I'll use for loop, right?

This how:

public partial class Form1 : Form
        List<string> listNames;
        public Form1()
            //some example data to populare dgv:
            dataGridView1.Columns.Add("col1", "name");
            dataGridView1.Columns.Add("col2", "age");
            dataGridView1.Rows.Add("mitja", "31");
            dataGridView1.Rows.Add("john", "28");
            dataGridView1.Rows.Add("sara", "22");            

        private void button1_Click(object sender, EventArgs e)
            listNames = new List<string>();
            foreach (DataGridViewRow row in dataGridView1.Rows)
                foreach (DataGridViewCell cell in row.Cells)
                    if (cell.ColumnIndex == 0) //SET YOUR PARTICULAR COLUMN INDEX HERE!!
                        if (cell.FormattedValue != String.Empty)
                            //add a name from 1st column (column with index 0):

            //show ann the names from the list:
            string strNames = null;
            foreach (string name in listNames)
                strNames += name + Environment.NewLine;
            MessageBox.Show("List of all names\n\n" + strNames);
This question has already been answered. Start a new discussion instead.