Create second column in Datatable

Asked

Viewed 246 times

3

I have a DataTable where with the code:

DT.Column.Add("1ª", gettype(int32))  
    For I = 1 To 30  
        DT.Rows.Add(I)  
    Next(I)

This For lists column 1 from 1 to 30. 'DT is declared with a new DataTable, in this case the Prog does everything right, but I would like to know if it is possible for me to add a second column without being through:

DT.Column.Add("1ª", gettype(int32))  
    For I = 1 To 30    
        DT.Rows.Add(I, I*2)    
    Next(I) 

This would be necessary as the formula in the second column varies according to the value of I on each line. Examples and/or help in C# are welcome.
Working with lines I dominate relatively well, but spine is always a headache for me.

I tried something like:

For I = 1 To 30  
    DT.Rows.Add(I)  
Next(I)  
DT.Column.Add("2ª", gettype(int32))
For I = 1 to 30
  DT.Rows.Add(I)
Next(I)

But without any success, it just creates column 2 and adds data to column 1.

  • I don’t understand the point. It’s creating a second column or putting data in it?

  • @jbueno precise popular the second column based on the data of the first. Popular numerous columns at a time (code 2) is quiet, but what I really need is to write code that allows the second column to be popular with limitations on the first. Example: When there is a I>10 he will do in the second column I/2. It became clearer the objective?

  • Wait, I’m processing hehe

  • @jbueno You have time, if you want you can look at Filipe’s answer suddenly try to help me even more.

1 answer

2


If I understand what you want, probably the solution is to do it this way:

DataTable DT = new DataTable();
DT.Columns.Add("1ª", typeof(int));
DT.Columns.Add("2ª", typeof(int));
for (int i = 0; i < 30; i++)
{
    var row = DT.NewRow();
    row["1ª"] = i;
    row["2ª"] = i;
    DT.Rows.Add(row);
}

Or that:

DataTable DT = new DataTable();
DT.Columns.Add("1ª", typeof(int));
DT.Columns.Add("2ª", typeof(int));
for (int i = 0; i < 30; i++)
{
    DT.Rows.Add(i, i);
}
  • I use VB.NET tried to translate the code you presented, I arrived at the following: For I = 1 And I > 10 To 30 &#xA; DT.Rows.Add(I, I / 2) &#xA; Next (I), He populates the second but he starts dividing everything already, but at least it’s a start thanks for the help.

  • @Alexnunes, the I will start the same for both, maybe you should change the logic of the iteration to suit what you need.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.