Murali Kris

Murali Kris

  • 1.9k
  • 213
  • 29.9k

Cross-thread operation not valid: Control ‘dataGridView1’

Nov 16 2018 3:16 AM
Hi Mates,
 
I would to get all some data from sharePoint site using win form for UI.
 
InFact i am getting expected output if not using Asynch, await(multi threading) but when i apply multi threading it thows below error.
 
Cross-thread operation not valid: Control 'dataGridView1' accessed from a thread other than the thread it was created on.
 
yes i am using data table to add columns, calling a function to add columns.
 
Actual Code from here :
 
private String lists() // function here for actual logic here to get data.
{
var st = "";
if (Global.sctx != null)
{
Web web = Global.sctx.Web;
Global.sctx.Load(web, w => w.Lists);
Global.sctx.ExecuteQuery();
ListCollection listcoll = web.Lists;
Global.sctx.Load(listcoll);
Global.sctx.ExecuteQuery();
addcolumnsdatatable(); // here calling method for add coulunms.
foreach (List list in listcoll)
{
var dr = dt.NewRow();
st = list.Title;
dr["List Names"] = list.Title;
dt.Rows.Add(dr);
}
dataGridView1.DataSource = dt; // error here with Cross-thread operation not valid
}
return string.Empty;
}
private async void button3_Click(object sender, EventArgs e)
{
Task<string> getliststhread = new Task<string>(lists);
getliststhread.Start();
label10.Text = "Loading lists please wait...";
var getLists = await getliststhread;
label10.Text = "List Exported Grid View Sucessfully...";
}
void addcolumnsdatatable() //adding columns here
{
dt.Columns.Add("List Names", typeof(String));
}
 
kindly help me here with peaice if script where to add, what should i add going forward to avoid errors.
 
thanks In Advance.

Answers (3)