简体   繁体   中英

Insert String Array Values Into DataGridView C#

I am developing a windows form application in C# . My Program will read the values from excel cells and insert the data into DataGridView to display the users.

After I have read the excel files, I get the results in string arrays. How can I insert into DataGridView?

private void btnImport_Click(object sender, EventArgs e)
    {
        Microsoft.Office.Interop.Excel.Application ExcelObj = null;
        ExcelObj = new Microsoft.Office.Interop.Excel.Application();

        if (ExcelObj != null)
        {
            if (tbxFileDirectory.Text != "")
            {
                Workbook workbook = ExcelObj.Workbooks.Open(
                openFD.FileName, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true);

                Sheets sheets = workbook.Worksheets;

                //Get excel sheet number
                Worksheet worksheet = (Worksheet)sheets.get_Item(1);

                for (int i = 6; i <= worksheet.UsedRange.Rows.Count; i++)
                {
                    Range range = worksheet.get_Range("A" + i.ToString(), "K" + i.ToString());

                    Array myvalues = (Array)range.Cells.Value;

                    string[] strArray = ConvertToStringArray(myvalues);

                    //INSERT INTO DATAGRIDVIEW
                }
                MessageBox.Show("File was imported successfully");
            }
            else
            {
                MessageBox.Show("Please select the file to import.");
            }
        }
        else 
        {
            MessageBox.Show("ERROR: EXCEL couldn't be started!");
        }
    }

My DataGrid has 4 columns, ProductID, ProductName, Price, & Qty. I want to insert these values, strArray[0], strArray[1], strArray[9] & strArray[10] in each of the column. How can I do this? Any help will be much appreciated!

你可以这样做

dataGridView1.Rows.Add(strArray[0],strArray[1]......);

DataGridView has performance issues when inserting strings directly, and it is awkward to manipulate the data if all you have is the data in the grid itself (though obviously you have to data you parsed from excel). You are usually better off putting the data into a DataTable and then bind that to the grid.

See Add new column and data to datatable that already contains data - c# if you need an example of stuffing data into a DataTable via code.

Binding is easy, assign the DataTable to the DataSource property of the grid.

If you get more than a few hundred rows, you may still see performance issues though -- however, by changing the logic to a virtualize the data see DataGridView live display of datatable using virtual mode for a simple example of that.

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