As an intermediate approach, try replacing the problematic line with:
BeginInvoke( new Action( ( ) => dataGridView1.DataSource = dt.DefaultView ) );
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I am copying excel sheet data from folder and displaying in datagridview without using database and getting error like this way
"System.InvalidOperationException: 'Cross-thread operation not valid: Control 'dataGridView1' accessed from a thread other than the thread it was created on.'"
Please find below the code
using ClosedXML.Excel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Threading;
namespace Image_Retrival
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var t = new Thread((ThreadStart)(() => {
using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Excel workbook|*.xlsx", Multiselect = false })
{
if (ofd.ShowDialog() == DialogResult.OK)
{
Cursor.Current = Cursors.WaitCursor;
DataTable dt = new DataTable();
using (XLWorkbook workbook = new XLWorkbook(ofd.FileName))
{
bool isfirstrow = true;
var rows = workbook.Worksheet(1).RowsUsed();
foreach (var row in rows)
{
if (isfirstrow)
{
foreach (IXLCell cell in row.Cells())
dt.Columns.Add(cell.Value.ToString());
isfirstrow = false;
}
else
{
dt.Rows.Add();
int i = 0;
foreach (IXLCell cell in row.Cells())
dt.Rows[dt.Rows.Count - 1][i++] = cell.Value.ToString();
}
}
dataGridView1.DataSource = dt.DefaultView;
Cursor.Current = Cursors.Default;
}
}
}
}));
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();
}
As an intermediate approach, try replacing the problematic line with:
BeginInvoke( new Action( ( ) => dataGridView1.DataSource = dt.DefaultView ) );