user123456789
user123456789

Reputation: 2004

Column added only works for first row in GridView

I am displaying my columns dynamically for my GridView and I want to add another column based off the values from two other columns. So the new column is the number of Jobs minus the number of POD. I was able to create the new column but it is only displaying results for the first row in the GridView and all the other rows are blank. Also is it possible to change the position of this column? It defaults to the last column but I would like it to be the 4th column in the GridView.

main.Columns.Add("NotPOD", typeof(int));
              int index = 0;
              foreach (DataRow row in main.Rows)
              {
                  main.Rows[index]["NotPOD"] = Convert.ToInt32(main.Rows[index]["Jobs"]) - Convert.ToInt32(main.Rows[index]["POD"]);
              } 

            gvResults.DataSource = main;
            gvResults.DataBind();

Upvotes: 0

Views: 1095

Answers (3)

Tufan Chand
Tufan Chand

Reputation: 752

Using foreach

main.Columns.Add("NotPOD", typeof(int));    
foreach (DataRow row in main.Rows)
{
   row["NotPOD"] = Convert.ToInt32(row["Jobs"]) - Convert.ToInt32(row["POD"]);
} 
gvResults.DataSource = main;
gvResults.DataBind();

Using for

main.Columns.Add("NotPOD", typeof(int));    
for(int index = 0;index < main.Rows.Count; index++)
{
   main.Rows[index]["NotPOD"] = Convert.ToInt32(main.Rows[index]["Jobs"]) - Convert.ToInt32(main.Rows[index]["POD"]);
} 
gvResults.DataSource = main;
gvResults.DataBind();

Upvotes: 2

M. Nasir Javaid
M. Nasir Javaid

Reputation: 5990

I guess a problem to resolve it update your index as

main.Columns.Add("NotPOD", typeof(int));
          int index = 0;
          foreach (DataRow row in main.Rows)
          {
              main.Rows[index]["NotPOD"] = Convert.ToInt32(main.Rows[index]["Jobs"]) - Convert.ToInt32(main.Rows[index]["POD"]);
              index++;
          } 

        gvResults.DataSource = main;
        gvResults.DataBind();

I hope it will help you

Upvotes: 0

HarryQuake
HarryQuake

Reputation: 163

Your code has a bug. When you use foreach, you have no need to use index. You also did not increment index

      foreach (DataRow row in main.Rows)
      {
          row["NotPOD"] = Convert.ToInt32(row["Jobs"]) - Convert.ToInt32(row["POD"]);
      } 

Upvotes: 1

Related Questions