Get data from each row of a column in C#

Asked

Viewed 1,682 times

9

Here’s the thing, I got a DataGridView with several columns. In each row of this DataGridView a program installation path will be shown. With this value displayed, I would like to use it to get the size of that folder and put it in a new column.

I have a method to calculate the size of a string:

private static long ObterTamanhoDiretorio(string tamanhoDir)
{
    DirectoryInfo dire = new DirectoryInfo(tamanhoDir.ToString());
    return dire.EnumerateFiles("*.*", SearchOption.AllDirectories).Sum(fi => fi.Length);
}

I don’t know if it’s something like this I have to use.

foreach (DataGridViewRow item in dataGridView1.Rows)
{

}

What I’d like to know is how to get that value by seeing on each line. If you have any ideas, thank you.

  • If you already have the paths on DataSource before setting in DataGridView, you can make a foreach directly into your data source, which should be a List or a DataTable. You can also use the event RowDataBound of DataGridView, which will read each row being rendered on the grid, so you can take the value of the column and move to its method to calculate the size.

  • How you fill the Datagridview?

2 answers

2

If you want to perform this action while loading the data you can use the event 'Onrowdatabound':

  gdvView.DataSource = Lista;
  gdvView.DataBind();


protected void GdvViewOnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[0].Text = "dados coluna 1";
            e.Row.Cells[1].Text = "dados coluna 2";
        }
    }

If you need to make the change after the Grid is filled, you can use the for or foreach.

  for (int i = 0; i < gdvView.Rows.Count; i++)
        {
            gdvView.Rows[i].Cells[0].Text = "novos dados";
        }

Or

 foreach (var row in gdvView.Rows)
        {
            ((gdvView)row).Cells[0].Text = "testeeeee";
        }

0

Using the @Cleidson_eng example, I did it in an application of mine to recover the values and go adding and at the end present the final value. If I help you in any way, follow:

protected void gvInscricoesCurso_RowDataBound(object sender, GridViewRowEventArgs e)
    {
      int total = 0;
      for (int i = 0; i < gvInscricoesCurso.Rows.Count; i++)
      {
        total += Convert.ToInt32(gvInscricoesCurso.Rows[i].Cells[1].Text);
        spanTotalInscritosGeral.InnerText = total.ToString();
        divTotalGeral.Visible = true;
      }
    }
  • In case I have solved your problem, mark as answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.