简体   繁体   中英

Convert 2D array to Byte array

I have a system that composed of two applications using Winforms in C#. The first application has shopping cart form that contains Gridview which displays product's information. The aim is to send the content of this Gridview to another Gridview in the second application via wireless. I searched and I found that I need to implement TCP socket programming (Asynchronous) approach and it was implemented successfull. However, the tutorials that I found are related to sending an object, I want to send 2D array which result from the Gridview. I plan to follow the following algorithm;

  1. Retrieve the product information in the Gridview.
  2. Reading the data from Gridview into 2D array "integer type".
  3. Convert 2D array to be Byte[], or using Buffer.BlockCopy Method in order to transmitted over the network.
  4. Receive the Byte array.
  5. Convert it to 2D array and fill the Gridview.
  6. Note; I want to send the ID of the customer in the transmission which was not included in the Gridview, I will take it from Public class.

This is my code

 var select = "SELECT Pro_ID, Price, Category_ID FROM Products where Empl_ID = 1";
            var c = new SqlConnection(); 
            var dataAdapter = new SqlDataAdapter(select, c);

            var commandBuilder = new SqlCommandBuilder(dataAdapter);
            var ds = new DataSet();
            dataAdapter.Fill(ds);
            dataGridView.DataSource = ds.Tables[0];
            dataGridView.Columns[0].HeaderText = "Items";
            dataGridView.Columns[1].HeaderText = "Price";
            dataGridView.Columns[2].HeaderText = "Quantity";

            // reading data from gridview into 2D array
            string[,] DataValue = new string[dataGridView.Rows.Count, dataGridView.Columns.Count];

            foreach (DataGridViewRow row in dataGridView.Rows)
            {
                foreach (DataGridViewColumn col in dataGridView.Columns)
                {
                    DataValue[row.Index, col.Index] = dataGridView.Rows[row.Index].Cells[col.Index].Value.ToString();
                }

            }

I was able to implement the first and second points, but the rest, I need some guidance to implement.

In C#, everything is an object. You can cast your 2D array as an object, send it as such, and then simply cast it back to a byte[,].

byte[,] localByteArray = new byte[someDimension,someOtherDimension];
object transmission = localByteArray;
//transmit

//reception scope, receives "transmission"
byte[,] decode = (byte[,])transmission;
//use decode as 2D array

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