表示datagridview中的byte数组

时间:2013-12-26 06:40:48

标签: c# arrays datagridview bytearray bmp

我在C#中有一个字节数组:

 byte[] bmp = File.ReadAllBytes("D:\\x.bmp");

我想在DataGridView中表示如下(三列 - 第一列偏移,第二列sizebyte,第三列描述,行是来自x.bmp的字节数组中的元素):

0          2               signature
2          4                size BMP
6          2                reserved
8          2                reserved
10         4                offset start image
14         4                must 40
18         4                 width
22         4                 height
26         2                 must 1

我可以使用C#中的DataGridView以这种方式表示字节数组吗?

2 个答案:

答案 0 :(得分:1)

我不是一个winform的人,所以我不知道如何使用DataGridView。 但我能以某种方式做到这一点:

这只是为了给你一个想法。

private void Form1_Load(object sender, EventArgs e)
        {
            byte[] offset = { 0, 2, 6, 8, 10, 14, 18, 22, 26 };
            byte[] sizebyte = { 4, 2, 2, 4, 4, 4, 4, 2 };
            string[] description = { "signature", "size BMP", "reserved", "reserved", "offset start image", "must 40", "width", "height" };

            this.dataGridView1.Columns.Add("offset", "offset");
            this.dataGridView1.Columns.Add("sizebyte", "sizebyte");
            this.dataGridView1.Columns.Add("description", "description");
            int i = offset.Length;


                for (int j = 0; j < i; j++)
                {
                    DataGridViewRow row = new DataGridViewRow();
                    row.CreateCells(dataGridView1);
                    row.Cells[0].Value = offset.GetValue(j).ToString();
                    if(j<sizebyte.Length)
                    row.Cells[1].Value = sizebyte.GetValue(j).ToString();
                    if (j < description.Count())
                    row.Cells[2].Value = description.GetValue(j).ToString();
                    dataGridView1.Rows.Add(row);
                }



        }

我知道代码并不完美。但是我可以用这个来填充我的dataGridView。

答案 1 :(得分:1)

这段代码怎么样?

您无需读取BMP文件的所有字节。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        UpdateDataGridView();
    }

    private void UpdateDataGridView()
    {
        byte[] bmp = new byte[28];
        List<BMPInfo> InfoList = new List<BMPInfo>();

        using (var fs = new FileStream("D:\\x.bmp", FileMode.Open, FileAccess.Read))
        {
            fs.Read(bmp, 0, bmp.Length);
        }

        InfoList.Add(new BMPInfo
        {
            Offset = BitConverter.ToInt32(bmp, 10),
            Size = BitConverter.ToInt32(bmp, 2),
            Description = "Something"
        });
        dataGridView1.DataSource = InfoList;
    }
}

public class BMPInfo
{
    public long Offset { get; set; }
    public long Size { get; set; }
    public string Description { get; set;}
}
相关问题