Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have written the following c# code to load the contents of the .DAT file to ListBox

Code:
C#
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
    struct file_record
    {

        public char Exch;
        public int ExchCode;
        public byte NameLength;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]
        public char[] ScripName;

    }


    private void button1_Click(object sender, EventArgs e)
    {

        OpenFileDialog ofd = new OpenFileDialog();
        string path = "";
        ofd.FileName = "";
        ofd.ShowDialog();
        path = ofd.FileName;

        if (string.IsNullOrEmpty(ofd.FileName))
        return;
        FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
        BinaryReader br = new BinaryReader(fs);

        int value = Marshal.SizeOf(typeof(file_record));


        var len = fs.Length;
        var num_records = len / value;
        file_record[] Bse = new file_record[num_records];
        Byte[] buffer = new Byte[Marshal.SizeOf(typeof(file_record))];
        for (int i = 0; i < num_records; i++)
        {
            fs.Read(buffer, 0, value);
            GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
            Bse[i] = (file_record)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(file_record));
            string abc = new string(Bse[i].ScripName);
            string str2 = abc.Substring(0, Bse[i].NameLength);
            listBox1.Items.Add(Bse[i].ExchCode + " " + str2);
            handle.Free();

        }

    }



I want to add the contents of the DAT File to DataGridView without using DataSource.Can anyone give me a code snippet to achieve this?

Thanks
Posted
Comments
Sergey Alexandrovich Kryukov 20-Oct-14 2:34am    
All this makes no sense. Why using InteropServices? You are merely reading a file.
Just populate data grid view. A cell has the property Value.
—SA
vivek murli 20-Oct-14 2:39am    
Thanks for replying Sergey.InterOpServices is required for using Structures

dataGridView1.Rows[i].Cells[0].Value = ?

1 solution

You have to go through a DataGridViewRow[^].

The DataGridView has a property "Rows" that has a function Add( ... ).

In order to use this "manual" way of adding rows you cannot set the DataSource propery. If you did set the DataSource property you need to change the DataSet, Table, ... in order to add the rows.

Hope this clarifies things for you.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900