2
col1    col2    col3
-----   -----   ----
1         4      7
2         5      8
3         6      9

Is there a way to build a datatable with the following way:

  1. add column 1 as "col1"
  2. add row for column 1 with value 1,2,3
  3. repeat for next column and its respective rows

I was trying to begin with following codes but got stuck at second column and its rows

dt.Columns.Add("col1")
dt.Rows.Add(1)
dt.Rows.Add(2)
dt.Rows.Add(3)
1
  • 1
    Please explain what you are trying to do better. What does the data look like before, so we can tell what you want to go where. Commented Sep 23, 2014 at 17:41

1 Answer 1

2

Once you've added columns and rows to your table, you can access the cells in each row by column index, which can be either a number or column name:

    dt.Columns.Add("col1")
    dt.Columns.Add("col2")
    dt.Columns.Add("col3")

    dt.Rows.Add(dt.NewRow())
    dt.Rows.Add(dt.NewRow())
    dt.Rows.Add(dt.NewRow())

    'Populate column 1 using index 0
    dt.Rows(0)(0) = 1
    dt.Rows(1)(0) = 2
    dt.Rows(2)(0) = 3

    'Populate column 2 using index 1
    dt.Rows(0)(1) = 4
    dt.Rows(1)(1) = 5
    dt.Rows(2)(1) = 6

    'Populate column 3 using column name as cell index for a change
    dt.Rows(0)("col3") = 7
    dt.Rows(1)("col3") = 8
    dt.Rows(2)("col3") = 9

    'Add and populate another column later
    dt.Columns.Add("col4")
    dt.Rows(0)("col4") = 97
    dt.Rows(1)("col4") = 98
    dt.Rows(2)("col4") = 99

    'Add and populate another row later
    dt.Rows.Add(dt.NewRow())
    dt.Rows(3)("col1") = 10
    dt.Rows(3)("col2") = 20
    dt.Rows(3)("col3") = 30
    dt.Rows(3)("col4") = 40
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.