简体   繁体   中英

C# SQL data from DataTable to Array

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?

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM