0

I have a program where logged in users can upload/dowload files. I want a query when a user is logged in, and store the data in an array. Here's my code:

 string query = "SELECT * FROM Login;";
        var valami = new DataTable();
        var con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Roland\Desktop\IBCONTROLL\BIZT.MENTÉS\program_1.7\db_connect_ver_1\login.mdf;Integrated Security=True");
        var sda = new SqlDataAdapter(query, con);
        sda.Fill(valami);
        var result = new string[valami.Columns.Count];
        DataRow dr = valami.Rows[1];
        for (var i = 0; i < dr.ItemArray.Length; i++)
        {
            result[i] = dr[i].ToString();
        }
        foreach (var t in result)
        {
            Console.WriteLine(t);
        }

The problem is that this is making an 1 dimension array, but I need a two dimension array, and use it later just as a table.
Can you please help me fix this code?

  • I don't really know how to use DataTables for this case, it would be easier with a 2D Array –  Oct 18 '17 at 16:52
  • 1
    Sounds like an excellent learning opportunity. – Dan Bracuk Oct 18 '17 at 16:54
  • You can see in that answer one solution for your question. https://stackoverflow.com/questions/8932900/datatable-to-multidimensional-array – Jorge Martins Oct 18 '17 at 17:03
  • Thank you very much @Vikhram Can i add your comment as an answer somehow? –  Oct 18 '17 at 17:11
  • If you would really prefer a 2D array, in C# they are declared using `var result = new string[dt.Columns.Count, dt.Rows.Count];` and assigned through a nested loop. You can also use `var result = new string[dt.Columns.Count][];` and assign each row with `result[i] = dr.ItemArray.Select(item => item.ToString()).ToArray()`. – Kevin K. Oct 18 '17 at 17:22

1 Answers1

0

You can store the DataTable instead of storing it as a 2-D array. There are multiple benefits to it. You can not only access the data by column name (which you cannot do in a 2-d array), but you will also have all metadata related to the query you fired, in the DataTable. Note that storing this metadata has a small memory overhead.

To access a given element you can write DataTable.Rows[rowNumber][columnNumber] or DataTable.Rows[rowNumber][columnName]

Vikhram
  • 4,294
  • 1
  • 20
  • 32