在填充TreeView时创建ProgressBar

时间:2019-06-19 17:39:56

标签: c# treeview progress-bar

当TreeView从数据库加载自身时,我需要创建一个简单的Progressbar,因为它的在线数据库需要一些时间才能显示包含此TreeView的窗体。

这是我所做的,但是不知道如何/在何处放置“ progressbar.PerformStep()”,或者很高兴知道如何做。

private void FormMain_Load(object sender, EventArgs e)
{
    String myConnectionString = "server=...";
    try
    {
        conn = new MySqlConnection(myConnectionString);
        String Sequel = "SELECT ...";
        MySqlDataAdapter da = new MySqlDataAdapter(Sequel, conn);
        DataTable dt = new DataTable();

        conn.Open();
        da.Fill(dt);

        foreach (DataRow dr in dt.Rows)
        {
            parentNode = MainTreeView.Nodes.Add(dr["NODNAME"].ToString());
            parentNode.Tag = ...;

            PopulateTreeView(Convert.ToInt32(dr["PARVAL"].ToString()), parentNode);
        }
    }
    catch (MySqlException ex)
    {
        MessageBox.Show(ex.Message);
    }
}

private void PopulateTreeView(int parentId, TreeNode parentNode)
{
    String Seqchildc = "SELECT PARVAL, SUBNODNAME, SUBNODVAL FROM subparentnod WHERE PARVAL=" + parentId + "";
    MySqlDataAdapter daChild = new MySqlDataAdapter(Seqchildc, conn);

    DataTable dtChild = new DataTable();
    daChild.Fill(dtChild);

    TreeNode childNode;
    foreach (DataRow dr in dtChild.Rows)
    {
        if (parentNode == null)
        {
            childNode = MainTreeView.Nodes.Add(dr["SUBNODNAME"].ToString());
            childNode.Tag = dr["SUBNODNAME"].ToString();
        }
        else
        {
            childNode = parentNode.Nodes.Add(dr["SUBNODNAME"].ToString());
            childNode.Tag = dr["SUBNODNAME"].ToString();
        }
        PopulateTreeView(Convert.ToInt32(dr["SUBNODVAL"].ToString()), childNode);
    }
}

这是我使用其他Form并使用Progress-bar和Action所做的事情。

public partial class frmWaitForm : Form
{
    public Action Worker
    {
        get;
        set;
    }

    public frmWaitForm(Action worker)
    {
        InitializeComponent();

        if (worker == null)
            throw new ArgumentNullException();
        Worker = worker;
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        Task.Factory.StartNew(Worker).ContinueWith(t => { this.Close(); }, 
            TaskScheduler.FromCurrentSynchronizationContext());
    }

    private void frmWaitForm_Load(object sender, EventArgs e)
    {
        this.ControlBox = false;
    }
}

然后:

using (frmWaitForm mFrmWaitForm = new frmWaitForm(RetriveDataFromDatabase))
            {
                mFrmWaitForm.ShowDialog(this);
            }

void RetriveDataFromDatabase()
        {
            MySqlConnection conn;
            MySqlCommand cmd;
         ...


        }

0 个答案:

没有答案