Click here to Skip to main content
15,882,152 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
---------------------------------------
Id | Name | Credit |
---------------------------------------
1 | A | -2 |
2 | B | 1 |
3 | c | -9 |
4 | d | 4 |
---------------------------------------

the above datatable split into below Datatable
---------------------------------------------------
Id | Name | AdvCredit | AdvCredit |
---------------------------------------------------
1 | A | -2 | |
2 | B | | 1 |
3 | c | -9 | |
4 | d | | 4 |
--------------------------------------------------

What I have tried:

i tried with ViewState but from view state to datatable values not converting but i want only in datatble split
Posted
Updated 23-Apr-18 23:39pm

If you interested in "converting" one datatable into another on client side, check this:
C#
//source datatable
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[]
	{
		new DataColumn("Id", typeof(int)), 
		new DataColumn("Name", typeof(string)), 
		new DataColumn("AdvCredit", typeof(int))
	});
dt.Rows.Add(new object[]{1, "A", -2});
dt.Rows.Add(new object[]{2, "B", 1});
dt.Rows.Add(new object[]{3, "c", -9});
dt.Rows.Add(new object[]{4, "d", 4});

//create destination datatable based on source datatable
DataTable dstdt = dt.Clone();
//add new column
dstdt.Columns.Add(new DataColumn("AdvCredit1", typeof(int)));
//allow nulls!
dstdt.Columns[2].AllowDBNull = true;
dstdt.Columns[3].AllowDBNull = true;

//default value when condition does not meet
int? defVal = null;
//copy data from source to destination datatable
dstdt = dt.AsEnumerable()
	.Select(x=> dstdt.LoadDataRow(new object[]
	{
		x.Field<int>("Id"),
		x.Field<string>("Name"),
		x.Field<int>("AdvCredit") < 0 ? x.Field<int>("AdvCredit") : defVal,
		x.Field<int>("AdvCredit") > 0 ? x.Field<int>("AdvCredit") : defVal,
	}, false))
	.CopyToDataTable();
 
Share this answer
 
Comments
Murali-Krishna-battu 25-Apr-18 7:36am    
Thank You Maciej Los
Maciej Los 25-Apr-18 7:38am    
You're very welcome.
Assuming your data comes from a database of some form, that's the place to do this.
SQL
SELECT ID, 
       CASE WHEN Credit < 0 THEN Credit ELSE NULL END,
       CASE WHEN Credit < 0 THEN NULL ELSE Credit END
FROM MyTable
 
Share this answer
 
Comments
Murali-Krishna-battu 25-Apr-18 7:36am    
Thanks OriginalGiff but i need in c#

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