在C#中将数据写入文本框时显示进度条

时间:2018-05-18 10:19:35

标签: c# textbox progress-bar

我必须在文本框中写一个长文本,屏幕冻结了很长时间。 所以我想在将文本写入文本框时显示进度条。我的代码有什么建议吗?谢谢!

\d{4}

4 个答案:

答案 0 :(得分:0)

您可以计算在等于满之前需要添加到进度的次数(设置为100或您选择的,称为最大值)。我会通过进度条执行此操作所需的更改为100(或最大值)除以DataRow中的行数。

from flask import Flask
from flask_admin.contrib.sqla import ModelView
from flask_sqlalchemy import SQLAlchemy
from faker import Faker
from flask_admin import Admin

app = Flask(__name__)

# Create in-memory database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)


# Flask views
@app.route('/')
def index():
    return '<a href="/admin/">Click me to get to Admin!</a>'


class Supplier(db.Model):
    __tablename__ = 'supplier'

    id = db.Column(db.Integer, primary_key=True)

    name = db.Column(db.Unicode(100), nullable=False)
    description = db.Column(db.UnicodeText(), nullable=True)

    products = db.relationship("Product", back_populates="supplier")

    def __str__(self):
        return unicode(self).encode('utf-8')

    def __unicode__(self):
        return self.name


class Product(db.Model):
    __tablename__ = 'product'

    id = db.Column(db.Integer, primary_key=True)

    name = db.Column(db.Unicode(100), nullable=False)
    code = db.Column(db.Unicode(32), nullable=False)
    description = db.Column(db.UnicodeText(), nullable=True)

    supplier_id = db.Column(db.Integer, db.ForeignKey('supplier.id'), index=True, nullable=False)
    supplier = db.relationship(Supplier, back_populates='products')

    def __str__(self):
        return unicode(self).encode('utf-8')

    def __unicode__(self):
        return self.name


class BaseView(ModelView):
    can_view_details = True

    column_formatters = {
        'description': lambda v, c, m, p: m.description.upper(),
    }


class SupplierView(BaseView):
    column_list = ('name', 'description', 'products')


class ProductView(BaseView):
    pass


class ProductNotInheritedView(ModelView):
    pass


admin = Admin(app, template_mode="bootstrap3")
admin.add_view(SupplierView(Supplier, db.session))
admin.add_view(ProductView(Product, db.session))
admin.add_view(
    ProductNotInheritedView(Product, db.session, name='Product Not Inherited', endpoint='product-not-inherited'))


@app.before_first_request
def build_sample_db():

    db.drop_all()
    db.create_all()

    fake = Faker()

    _suppliers = []
    for _ in range(20):
        _supplier = Supplier(
            name=fake.company(),
            description=fake.paragraph(nb_sentences=fake.random.randint(1, 10))
        )
        _suppliers.append(_supplier)
        for _ in range(fake.random.randint(1, 10)):
            _supplier.products.append(
                Product(
                    name=' '.join(fake.words(nb=fake.random.randint(1, 5))),
                    description=fake.paragraph(nb_sentences=fake.random.randint(1, 10)),
                    code=fake.isbn10(separator="-")
                )
            )

    db.session.add_all(_suppliers)

    db.session.commit()


if __name__ == '__main__':
    app.run(port=5000, debug=True)

然后在你的Foreach中我会使用这个ProgBarChange值增加你的进度条。

ProgBarChange = progBar.Maximum / DataRow.Count()

请记住清除progBar,就像使用txtResults.Clear()一样。

progBar.Value += ProgBarChange;

答案 1 :(得分:0)

您应该将BackgroundWorker用于aysnc进程

delegate void SetTextCallback(string text);
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        backgroundWorker1.WorkerReportsProgress = true;
        backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
        backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
    }
    void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        // Your background task goes here
        for (int i = 0; i <= 100; i++)
        {
            SetText(i.ToString()+" %");
            backgroundWorker1.ReportProgress(i);
            System.Threading.Thread.Sleep(100);
        }
    }
    void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progressBar1.Value = e.ProgressPercentage;
    }
    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        MessageBox.Show("MEssagebox");
    }
    private void button1_Click(object sender, EventArgs e)
    {
        backgroundWorker1.RunWorkerAsync();
    }

    private void SetText(string text)
    {
        if (this.textBox1.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(SetText);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            this.textBox1.Text = text;
        }
    }
}

注意:当数据从数据库检索并写入文本框时,需要继续运行进度条。

答案 2 :(得分:0)

您应该使用BackgroundWorker来更新进度。

答案 3 :(得分:0)

这是一个客户端功能。如果可能,请尝试以下简单的java脚本进度条。

<html>
<head>
    <style>
        #ProgressBar {
            width: 100%;
            background-color: #ddd;
        }
        #Bar {
            width: 1%;
            height: 30px;
            background-color: #4CAF50;
        }
    </style>
    <meta charset="utf-8" />
    <script>
        function showProgress() {
            var element = document.getElementById("Bar");
            var width = 1;
            var id = setInterval(frame, 10);
            function frame() {
                if (width >= 100) {
                    clearInterval(id);
                } else {
                    width++;
                    element.style.width = width / 2 + '%';
                }
            }
        }
    </script>
</head>
<body>
    <div id="ProgressBar">
        <div id="Bar"></div>
    </div>
    <br>
    <input type="text" id="txtResults" onkeypress="showProgress()" />
</body>
</html>