I trying to fire my datagridview
with records from sql server database
using a store procedure
with two parameters id. I have two comboboxes which takes the parameters and a button. As data is being fetched, I would like to see the progress so I assigned a progressBar
to it but I am getting an Error: Invalid thread cross process : The access to the control ComboBox2 performed by a different thread than the thread for which it was created.
My c# code:
private void button2_Click(object sender, EventArgs e)
{
ProgressBar1.Visible = true;
ProgressBar1.Style = ProgressBarStyle.Marquee;
System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(loadTable));
thread.Start();
}
private void loadTable()
{
// Load Table...
string C = ConfigurationManager..["DB"].ConnectionString;
SqlConnection con = new SqlConnection(C);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = ("[dbo].[spInfo]");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Periode2", comboBox2.SelectedValue.ToString());
cmd.Parameters.AddWithValue("@Periode1", comboBox3.SelectedValue.ToString());
try
{
// Open connection
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// Save the results in the DT. Call the adapter statement and fill it in the DT
DataTable dt = new DataTable();
adapter.Fill(dt);
setDataSource(dt);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
internal delegate void SetDataSourceDelegate(DataTable dt);
private void setDataSource(DataTable dt)
{
// Invoke method if required:
if (this.InvokeRequired)
{
this.Invoke(new SetDataSourceDelegate(setDataSource), dt);
}
else
{
datagridview1.DataSource = dt;
ProgressBar1.Visible = false;
}
}
I would really appreciate any help it thanks.