Click here to Skip to main content
15,894,955 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
how to multiply datatable column with all column for same datatble columns:


my datatable is:

col4 	col3	col2	col1
8	         5	 1	 1
9	         2		
7	         4		



expected result:
col4	col3	col2	col1
     8	          5	 1	 1
     8	          2	 1	 1
     8	          4	 1	 1
     9	          5	 1	 1
     9	          2	 1	 1
     9	          4	 1	 1
     7	          5	 1	 1
     7	          2	 1	 1
     7	          4	 1	 1


What I have tried:

C#
for (var v = 0; v < dt.Rows.Count; v++)
{
	int s = 0;
	for (var k = dt.Columns.Count; k > 0; k--)
	{
		DataRow d = dtRecord.NewRow();
		if (dtRecord.Columns.Contains(dt.Columns[k - 1].ToString()))
		{
			d[dt.Columns[k - 1].ToString()] = dt.Rows[v][dt.Columns[k - 1].ToString()].ToString();
			if (s == 0)
				dtRecord.Rows.Add(d);
			else
				dtRecord.Rows[v][dt.Columns[k - 1].ToString()] = dt.Rows[v][dt.Columns[k - 1].ToString()].ToString();
			s++;
		}
	}

}<pre>
Posted
Updated 23-Aug-17 4:54am
v2
Comments
ZurdoDev 23-Aug-17 11:29am    
It would probably be easier to do it in sql first. But, why isn't your code working?
Graeme_Grant 23-Aug-17 11:43am    
It is unclear how the data is being generated or what type of app it is being used in as no context is given... It could be UI generated rather than db ...

1 solution

This should help: DataColumn.Expression Property (System.Data)[^] and this: Creating Expression Columns | Microsoft Docs[^] (code samples included)

UPDATE: If you mean auto-populate, then you need to do that manually - take the data from your original DataTable and generate a new one... Something like this:
C#
DataTable ExpandDataTable(DataTable dt)
{
    var dt = new DataTable();
    // configure columns
    // iterate and build new DataTable
    return dt;
}
 
Share this answer
 
v2
Comments
Member 10371658 23-Aug-17 10:27am    
not helpful, as i am expecting.
Graeme_Grant 23-Aug-17 10:53am    
What are you expecting?
Member 10371658 25-Aug-17 12:36pm    
i have the following data table:
col4 col3 col2 col1
8 5 1 1
9 2
7 4
expecting result:
col4 col3 col2 col1
8 5 1 1
8 2 1 1
8 4 1 1
9 5 1 1
9 2 1 1
9 4 1 1
7 5 1 1
7 2 1 1
7 4 1 1

Every column multiply with all other column which is make the unique row. see the above tables

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