Sumit Goyal
Sumit Goyal

Reputation: 165

how to read data from one column of datagridview

I want to read data from one column of datagridview. My datagridview contains many columns but I want to read all cells but only from one column. I read all columns using this code:

foreach (DataGridViewColumn col in dataGridView1.Columns)
        col.Name.ToString();

But I want to read all cell from particular column.

Upvotes: 12

Views: 73118

Answers (5)

Zujaj Misbah Khan
Zujaj Misbah Khan

Reputation: 809

FOREACH LOOP

string data = string.Empty;
string data = string.Empty;
int indexOfYourColumn = 0;
int indexOfYourColumn = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
foreach (DataGridViewRow row in dataGridView1.Rows)
   data = row.Cells[indexOfYourColumn].Value;

FOR LOOP

using System.Collections;

string data = string.Empty;
int indexOfYourColumn = 0;

IList list = dataGridView1.Rows;

for (int i = 0; i < list.Count; i++)
{
  DataGridViewRow row = (DataGridViewRow)list[i];
   data = row.Cells[indexOfYourColumn].Value;
  data = Convert.ToDecimal(row.Cells[indexOfYourColumn].Value);
}

Upvotes: 0

user2673536
user2673536

Reputation: 11

To get the value of the clicked cell:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        textBox1.Text = dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString();
    }

Upvotes: 0

SysDragon
SysDragon

Reputation: 9888

Maybe this helps too. To get one cell:

string data = (string)DataGridView1[iCol, iRow].Value;

Then you can simply loop rows and columns.

Documentation.

Upvotes: 19

Rohit
Rohit

Reputation: 10236

try this

foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            foreach (DataGridViewCell cell in row.Cells)
            {
                if (cell.ColumnIndex == 0) //Set your Column Index
                {
                //DO your Stuff here..
                }
            }
         }

or the other way

       foreach (DataGridViewColumn col in dataGridView1.Columns)
            {
                if (col.Name == "MyColName")
                {
               //DO your Stuff here..
                }
            }

Upvotes: 2

yogi
yogi

Reputation: 19591

Try this

string data = string.Empty;
int indexOfYourColumn = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
   data = row.Cells[indexOfYourColumn].Value;

Upvotes: 24

Related Questions