将2D数组转换为字节数组

时间:2017-03-30 16:57:28

标签: c# arrays

我有一个系统,它由两个在C#中使用Winforms的应用程序组成。第一个应用程序具有购物车表单,其中包含显示产品信息的Gridview。目的是通过无线将此Gridview的内容发送到第二个应用程序中的另一个Gridview。我搜索并发现我需要实现TCP套接字编程(异步)方法,并且它已成功实现。但是,我发现的教程与发送对象有关,我想发送从Gridview得到的2D数组。我计划遵循以下算法;

  1. 在Gridview中检索产品信息。
  2. 将Gridview中的数据读入2D数组“整数类型”。
  3. 将2D数组转换为Byte [],或使用Buffer.BlockCopy方法以便通过网络传输。
  4. 接收字节数组。
  5. 将其转换为2D数组并填充Gridview。
  6. 注;我想在Gridview中发送未包含在Gridview中的客户ID,我将从Public类中获取它。
  7. 这是我的代码

     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();
                    }
    
                }
    

    我能够实现第一和第二点,但其余的,我需要一些指导来实现。

1 个答案:

答案 0 :(得分:0)

在C#中,一切都是对象。您可以将2D数组转换为对象,然后将其发送,然后将其转换回字节[,]。

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

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