Click here to Skip to main content
15,888,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello to all

i have a datagrid (from sql) with a datatable like this example :

name surname class

rick summer 3
pam Winter 5
erik frost 8

i need to change in this datagrid the column class to other value

if class is like 3 it will show a
if class is like 5 it will show b
if class is like 8 it will show c

i did it with the solution below, but it takes a lot of time when i have a lot rows, around 8000.

can anyone show me a better solution?

thanks in advance

What I have tried:

DataTable dt = Consumptionall(); //from sql connection
 dtAll = dt.Clone();
 dtAll.Columns["class"].DataType = typeof(string);
 foreach (DataRow drdc in dt.Rows)
 {
     dtAll.ImportRow(drdc);
     allconversion();
 }


private void allconversion()
       {
               for (int i = 0; i < dtAll.Rows.Count; i++)
               {
                   if (dtAll.Rows[i]["class"].ToString() == "3")
                   { dtAll.Rows[i]["class"] = "a"; }
                   if (dtAll.Rows[i]["class"].ToString() == "5")
                   { dtAll.Rows[i]["class"] = "b"; }
                   if (dtAll.Rows[i]["class"].ToString() == "8")
                   { dtAll.Rows[i]["class"] = "c"; }
Posted
Updated 13-Mar-18 4:11am

Use a CASE statement in your SQL query:
SQL
SELECT
    name,
    surname,
    CASE class
        WHEN 3 THEN 'a'
        WHEN 5 THEN 'b'
        WHEN 8 THEN 'c'
        ELSE Convert(varchar(10), class)
    END As class
FROM
    YourTable
;

CASE (Transact-SQL) | Microsoft Docs[^]
 
Share this answer
 
Comments
Maciej Los 13-Mar-18 10:11am    
5ed!
In addition to solution#1 by Richard Deeming[^], you can add computed/expression column to your DataTable object. Please, read:
Creating Expression Columns | Microsoft Docs[^]
DataColumn.Expression Property (System.Data)[^]

It's quite simple to achieve that:
VB.NET
Dim dc AS DataColumn = New DataColumn("ClassName", Type.GetTYpe("System.String"))
dc.Expression = "IIF(class=3, 'a', IIF(class=5, 'b', IIF(class=8, 'c', 'uknknown')))"
dtAll.Columns.Add(dc)


That's all!
 
Share this answer
 
v2
Comments
RickZeeland 13-Mar-18 10:13am    
5d !
Maciej Los 13-Mar-18 10:14am    
Thank you, Rick!

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