New to c#. I have a winform with a combobox, button and progress bar. On the button click event text is taken from the textbox and used in a sql query. While this query is running, I would like a progress bar (marquee - does not need to show % complete) to animate, when the query is complete I would like it to stop.
I have tried the below code but get the error:
‘跨线程操作无效:控件’cbTest‘从 线程而不是在其上创建它的线程.
private System.Windows.Forms.ProgressBar _progressBar;
public Test()
{
InitializeComponent();
_progressBar = progressBar;
}
private void Form1_Load_1(object sender, EventArgs e)
{
_progressBar.Style = ProgressBarStyle.Marquee;
_progressBar.MarqueeAnimationSpeed = 0;
}
public async void btn_Click(object sender, EventArgs e)
{
await Task.Run(() => GetValues(_progressBar));
}
private void GetValues(System.Windows.Forms.ProgressBar progressBar)
{
progressBar.Invoke(new System.Action(() =>
{
progressBar.MarqueeAnimationSpeed = 30;
}));
Sql.SqlQuery("exec Test..sp_Test " + cbTest.Text);
progressBar.Invoke(new System.Action(() =>
{
progressBar.Style = ProgressBarStyle.Blocks;
progressBar.Style = ProgressBarStyle.Marquee;
progressBar.MarqueeAnimationSpeed = 0;
}));
}
public static void SqlQuery(string queryString, string connectionString = "Data Source= Test; Initial Catalog = Test; Integrated Security = True")
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.CommandTimeout = 300;
command.Connection.Open();
command.ExecuteNonQuery();
}
}