Insert Data Into DataTable


  • Following advice from @Ante Meridian in another thread I had I am not struggling to get my data to insert into a DataTable properly.  I fear it is how my foreach loop is set-up.  This is the code I am using

       if(ro.GameInfoList != null)
          foreach(GameInfo info in ro.GameInfoList)
             //int id = info.gameid;
             //string name = info.gamename;
    		 DTTest.Rows.Add(info.gameid, info.gamename);

    However, the code is inserting in my datatable the data like this

    Row 1: gameid

    Row 2: gamename

    Row 3: gameid

    Row 4: gamename

    Instead of pairs being input toether like this

    Row 1: gameid, gamename

    Row 2: gameid, gamename

    How should my syntax be ammended in order to insert into the datatable the proper way?

    Sunday, April 9, 2017 9:59 PM


  • Best way to know is use the debugger, otherwise the code you posted looks fine e.g.

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Windows.Forms;
    namespace CheckListBoxFromSQL_Server
        public partial class MainForm : Form
            List<Game> GameInfoList ;
            DataTable DTTest;
            public MainForm()
            private void MainForm_Load(object sender, EventArgs e)
                DTTest = new DataTable();
                DTTest.Columns.Add(new DataColumn() { ColumnName = "C1", DataType = typeof(int) });
                DTTest.Columns.Add(new DataColumn() { ColumnName = "C2", DataType = typeof(string) });
                GameInfoList = new List<Game>()
                    new Game() { gameid = 1, gamename = "111" },
                    new Game() { gameid = 2, gamename = "222" }
                foreach (Game game in GameInfoList)
                    DTTest.Rows.Add(new object[] { game.gameid, game.gamename });
                dataGridView1.DataSource = DTTest;
        public class Game
            public int gameid { get; set; }
            public string gamename { get; set; }

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    • Marked as answer by IndigoMontoya Monday, April 10, 2017 12:00 AM
    Sunday, April 9, 2017 10:32 PM