I'm trying to populate a grid from a list of anonymous type instances. I want to apply threading as this makes my application to freeze while populating the results. But I keep getting this this error:
list of anonymous type instances Control 'gridHotelDetails' accessed from a thread other than the thread it was created on.
I've marked the line where the error is occuring. My Code:
public Thread MyThread { get; private set; }
public string search { get; set; }
public string searchCity { get; set; }
public string searchState { get; set; }
private void crawl()
{
if (CheckForInternetConnection())
{
if (string.IsNullOrEmpty(search) || string.IsNullOrEmpty(search) || string.IsNullOrEmpty(searchCity) || string.IsNullOrWhiteSpace(searchCity) || string.IsNullOrEmpty(searchState) || string.IsNullOrWhiteSpace(searchState))
{
MessageBox.Show("Please fill up the search criterias");
}
else
{
string url = string.Format("http://www.yellowpages.com/{0}/hotels?g={1}&q={2}", searchCity, searchCity, search);
if (!isURLExist(url))
{
MessageBox.Show("No records found. Please try again.");
}
else
{
Pages htmlDoc = new Pages(url);
htmlDoc.pageResults();
string searchUrl = string.Empty;
for (int ii = 1; ii <= 1; ii++)
{
searchUrl = url + "&page=" + ii;
htmlDoc.findHotels(searchUrl);
List<string> Name = htmlDoc.Names;
List<string> Address = htmlDoc.Address;
List<string> City = htmlDoc.City;
List<string> State = htmlDoc.State;
List<string> Zip = htmlDoc.Zip;
List<string> Phone = htmlDoc.Phone;
List<string> Website = htmlDoc.Website;
var CompleteInformation = Name.Zip(Address, (n, a) => new { Address = a, Name = n })
.Zip(City, (p, c) => new { p.Address, p.Name, City = c })
.Zip(State, (q, s) => new { q.Address, q.Name, q.City, State = s })
.Zip(Zip, (r, z) => new { r.Address, r.Name, r.City, r.State, Zip = z })
.Zip(Phone, (t, p) => new { t.Name, t.Address, t.City, t.State, t.Zip, Phone = p })
.Zip(Website, (u, w) => new { u.Name, u.Address, u.City, u.State, u.Zip, u.Phone, Website = w })
.ToList();
int rowCount = gridHotelDetails.Rows.Count;
foreach (var detail in CompleteInformation)
{
// Error occuring in this line
gridHotelDetails.Rows.Add(rowCount++, detail.Name, detail.Address, detail.City, detail.State, detail.Zip, detail.Phone, detail.Website);
}
}
}
UseWaitCursor = false;
}
}
else
{
MessageBox.Show("Internet Connection Not Available");
}
}
private void btnSearch_Click(object sender, EventArgs e)
{
search = txtSearch.Text.Trim();
searchCity = txtCity.Text.Trim();
searchState = ddState.Text.Trim();
MyThread = new Thread(new ThreadStart(crawl));
MyThread.Start();
gridHotelDetails.Visible = true;
}
Why is this error occurring and how can I solve this error ?