在执行SQL查询时显示进度条

11

我想在从SQL数据库读取数据时通知用户,并决定创建一个带有进度条的表单,但它不起作用 - 可能需要一个线程。我想以编程方式创建该表单。

        ProgressBar pb = new ProgressBar();

        pb.MarqueeAnimationSpeed = 30;
        pb.Style = ProgressBarStyle.Marquee;
        pb.Dock = DockStyle.Fill;

        progressForm.ClientSize = new Size(200, 50);
        progressForm.FormBorderStyle = FormBorderStyle.FixedDialog;
        progressForm.StartPosition = FormStartPosition.CenterScreen;
        progressForm.Controls.Add(pb);
        progressForm.ControlBox = false;
        progressForm.TopMost = true;

        progressForm.Show();  
        //do data processes here (all queries and executes)
        progressForm.close();

如何修改上面的代码以实现我的目标?

编辑:顺便说一句,我希望在项目中的每个数据函数中都使用这个进度条表单。例如:fillGrid,runQuery等。

@Will非常感谢你的回答。我的意思是如何使用类的函数,例如我的gridFill函数在那个连接类中:

 class ConnectionClass
    {
       public static SqlConnection connection = new SqlConnection();

    public string sorgu;
    public static string server;
    public static string userId;
    public static string catalog;
    public static string password;
    public static string accessMethod;
    public DataSet ds = new DataSet();
    Form progressForm = new Form();       

    public bool Open()
    {
        try
        {
            if (connection.State != ConnectionState.Open)
            {

                connection.ConnectionString = "Data Source = " + server + ";" +
                                              "Initial Catalog=" + catalog + ";" +
                                              "User ID=" + userId + ";" +
                                              "Password=" + password + ";" +
                                              "Connect Timeout=0";

                connection.Open();
                return true;
            }
            else
            {
                return true;
            }


        }
        catch (Exception ex)
        {
            MessageBox.Show("System message:" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return false;
        }

    }

    public DataTable Dt(string query)
    {
        DataTable dt = new DataTable();
        if (Open())
        {
            SqlDataAdapter da = new SqlDataAdapter(query, connection);
            try
            {   
                //progressForm.Showdialog()  is this possible???
                da.Fill(dt);
                //progressForm.close(); ??
            }
            catch (Exception ex)
            {
                MessageBox.Show("Sistem Mesajı:" + ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }         
        return dt;
    }

    public bool Run(string query, string hataMsj)
    {
        Form activeForm = Form.ActiveForm;
        query = " SET DATEFORMAT DMY " + query;

        SqlCommand sc = new SqlCommand(query, connection);
        try
        {
            Open();
            sc.ExecuteNonQuery();
            return true;
        }           
        catch (Exception )
        {
            return false;
        }
    }

    public void fillComboBox(string sorgu, ComboBox cb, string text, string value)
    {
        DataTable dt = Dt(sorgu);

        cb.DisplayMember = text;
        cb.ValueMember = value;
        cb.DataSource = dt;
        if (cb.Items.Count > 0)
        {
            cb.SelectedIndex = 0;
        }

    }

    public int fillGridView(string sorgu, DataGridView dgv)
    {
        DataTable dtGrvw = Dt(sorgu);
        dgv.DataSource = dtGrvw;
        return 1;
    }       
    }

另一个表单(类)中的示例查询

   ConnectionClass cc = new ConnectionClass();

    query= "  INSERT INTO tblPersonel (" +
                                          " [sqlUserName] " +
                                          ",[personelNo] " +
                                          ",[ad] " +
                                          ",[soyad] " +
                                          ",[departmanId] " +
                                          ",[emailadres] " +
                                          ",[tcKimlikNo],[kangurubu],[dokumaciNo])VALUES" +
                                          "('" + tbSqlUserName.Text +
                                          "','" + tbPersonelNo.Text +
                                          "','" + tbAd.Text +
                                          "','" + tbSoyad.Text +
                                          "','" + cbDepartman.SelectedValue.ToString() +
                                          "','" + tbMail.Text +
                                          "','" + tbKimlikno.Text + 
                                          "','" + tbKangrubu.Text + 
                                          "','" + tbDokumaciNo.Text + "' ) ";
                    if (cc.Run(query, "Unexpected error on insert new person"))
                    {
                        fillGrid();
                        this.Close();

                    }

    public void fillGrid()
    {
        query= " select * from View_Personel order by personelNo desc";
        cc.fillGridView(query, gridviewPersonel);
    }

我无法想象如何在bw_DoWork事件中使用它,因为我的函数有参数(查询,网格视图)。当我从另一个类中调用它时,我可以带着这些参数使用它...

p.s.:这个方法对我很有效,但它没有起作用。我不明白问题出在哪里。


7
请查看背景工作器类。http://msdn.microsoft.com/zh-cn/library/cc221403(v=vs.95).aspx - Ash Burlaczenko
2个回答

4
使用BackgroundWorker类填充您的DataGrid。
     Form progressForm;

     public void func() {
        BackgroundWorker bw = new BackgroundWorker ();
        bw.DoWork += new DoWorkEventHandler (bw_DoWork);
        bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler (bw_RunWorkerCompleted);

        progressForm = new Form ();

        ProgressBar pb = new ProgressBar ();

        pb.MarqueeAnimationSpeed = 30;
        pb.Style = ProgressBarStyle.Marquee;
        pb.Dock = DockStyle.Fill;

        progressForm.ClientSize = new Size (200, 50);
        progressForm.FormBorderStyle = FormBorderStyle.FixedDialog;
        progressForm.StartPosition = FormStartPosition.CenterScreen;
        progressForm.Controls.Add (pb);
        progressForm.ControlBox = false;
        progressForm.TopMost = true;

        progressForm.Show ();

        string queryString = "SELECT ...."; // fill query string here
        var params = new KeyValuePair<GridControl, string>(sorgu, queryString);
        bw.RunWorkerAsync (params);
    }

    void bw_DoWork (object sender, DoWorkEventArgs e) {
        KeyValuePair<GridControl, string> params = e.Argument as KeyValuePair<GridControl, string>;
        ConnectionClass cc = new Connection Class();
        cc.fillGrid(params.Value, params.Key);
    }

    void bw_RunWorkerCompleted (object sender, RunWorkerCompletedEventArgs e) {
        progressForm.Close (); //
    }

可以向BackgroundWorker发送参数。如果您需要多个参数,可以发送一个包含所需任何对象的元组。

编辑:如果您使用3.5,则可以使用KeyValuePair。代码已更新。


谢谢你的评论,它很有效。但是我有一个小问题。我的数据填充函数在一个类中,并且需要两个参数(查询和网格控件),我在项目中的任何地方都会使用它。public void fillGridControl(string sorgu, GridControl gc) {
BindingSource dataSource = new BindingSource(Dt(sorgu), null); gc.DataSource = dataSource;
}我能否将此函数放入bw_DoWork事件中?
- Rapunzo
1
@Rapunzo,你可以直接在bw_DoWork事件中调用fillGridControl函数。我不知道你的代码,但是有没有什么原因导致这样做行不通呢? - Will
我也更新了我的问题并附上了代码,如果您能看一下,我将不胜感激。 - Rapunzo
再次更新,应该是你所需要的。 - Will
我认为这个Tuple类没有包含在.Net 3.5中,所以我仍然无法完成它... - Rapunzo
我能不能在我的DataTable Dt函数中使用以下方法:
progressForm.Showdialog()
da.Fill(dt); progressForm.close();
- Rapunzo

1

就像 Ash Burlaczenko 建议的那样,您需要使用 BackgroundWorker 来实现这个目的。

但是,既然您想将其与 ProgressBar 结合起来,我建议您查看 CodeProject 上的这篇文章:ProgressWorker

它非常易于使用,并自动更新进度条。您需要做的就是记得不时调用 ProgressWorker.ReportProgress 方法以更新关联的进度条。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接