Click here to Skip to main content
15,897,519 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have one datatable. it contains 100 columns.

the problem is i don't want to check all the columns in the table.

I just want to check column from 25 to 50 in sequence.

finally i have the score and that i want to compare in that column (25 to 50) values.

if any score value is matching then we want to return find the  column name.

How to do this using data row.

below is code for sample.

                           

val1	val2	val3	…	…	val25	val26	…	val100
80	100	20	90	20	90	80	40	30




int Score = 80;

 foreach (DataRow row in result)

    {
         // Here i want to check row[25] to row[50]

         
   }

Output : val26 (if it is matching values then return column name)

(val26 is a columnname)


What I have tried:

foreach (DataRow row in result)

   {
        // Here i want to check row[25] to row[50]


  }
Posted
Updated 13-Oct-17 0:37am
v2
Comments
Richard MacCutchan 13-Oct-17 6:21am    
Just use a normal for loop of columns from 25 to 50.

If you want to check a specific range, don't use a foreach, use a for instead:
foreach (DataRow row in result)
     {
     for (int colIndex = 25; colIndex <= 50; colIndex++)
         {
         Console.WriteLine(row[colIndex]);
         Console.WriteLine(myDataTable.Columns[colIndex].ColumnName);
         }
     }
 }
 
Share this answer
 
Comments
gani7787 13-Oct-17 8:08am    
In my table some of the columns has null values.

when i am executing i getting error

Error : Object cannot be cast from DBNull to other types.

for (int colIndex = 5; colIndex <= 35; colIndex++)
{
double str1 = Convert.ToDouble(row[colIndex]); // Error : Object cannot be cast from DBNull to other types.
if (str1 == Score)// compare maxvalue
{
ColName = dt.Columns[colIndex].ColumnName;
break; // if matching the value then get the columnname and then exit the loop
}
}

How to handle null values if the column and rows has null values...
OriginalGriff 13-Oct-17 8:14am    
So check if the value in the cell is DBNull.Value before you cast it...
gani7787 13-Oct-17 8:46am    
Thanks. it's working...
OriginalGriff 13-Oct-17 10:09am    
You're welcome!
try
foreach (DataRow row in dt.Rows)
           {
               for (int i = 25; i <= 50; i++)
               {
                   if (row[25].ToString() == Score.ToString())
                   {
                       string columnName = dt.Columns[i].ColumnName;
                       // your code..
                   }
               }
           }
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900