roee oselka
roee oselka

Reputation: 21

I need to go through each and every row of a datatable

I have a data table named dt which is a SQL table converted.

All the data was sent from the server so I had to encrypt it. Now I need to decrypt every cell.

I wanted to do it like this:

foreach (DataRow row in dt.Rows)
{
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        row[i] = r.Decrypt(row[i].ToString());
    }
}

Decrypt works fine but row[i] = r.Decrypt(row[i].ToString()); give me the number of the column instead of its content, how do I get the content?

to make the post make more sense.

i want row[i] = r.Decrypt(a string representing the value of row[i]);

Upvotes: 0

Views: 692

Answers (3)

user19087368
user19087368

Reputation: 53

This is the correct way to interact with a datatable

  foreach(DataRow row in dt .Rows)
    {
        foreach(DataColumn column in dt .Columns)
        {
            Console.WriteLine(row[column]);
        }
    }

In your case you are literally passing an int to your row, because You are using count property.

** Edit This is in case Your datarow contains an object.

 DataTable dt = new DataTable();
            dt.Columns.Add("Column 1");
            dt.Columns.Add("Column 2");
            DataRow dataRow = dt.NewRow();
            dataRow.ItemArray = new object[]{"line 1 column 1", "line 1 column 2"
            };
            dt.Rows.Add(dataRow);

            foreach (DataRow row in dt.Rows)
            {
                foreach (DataColumn column in dt.Columns)
                {
                    var text = row[column.ToString()];

                    Console.WriteLine(text);
                }
            }

Result enter image description here

If none of this work, We would have to see how Your data row is created.

Upvotes: 1

roee oselka
roee oselka

Reputation: 21

 for (int i = 0; i < dt.Rows.Count ; i++)
        {
            for (int j = 1; j < dt.Columns.Count ; j++)
            {
                string cellValue = dt.Rows[i][j].ToString();
                dt.Rows[i][j] = r.Decrypt(cellValue);


            }
        }

Upvotes: 0

ironman
ironman

Reputation: 1066

As you mentioned that the other logic (Decrypt) is working fine and you just need to fetch the column content/values then you can try something like:

   foreach(DataRow row in table.Rows)
   {
      foreach(DataColumn column in table.Columns)
      {
          // you can insert your logic to use column value row[column] here
          Console.WriteLine(row[column]);
      }
    }

Upvotes: 0

Related Questions