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()
        {
            InitializeComponent();
              
            //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):
                            listNames.Add(cell.Value.ToString());
                    }
                }
            }

            //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);
        }
    }
commented: tnx +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.