用户界面没有响应或更新 [英] The user interface is not responding or updating

查看:68
本文介绍了用户界面没有响应或更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,伙计们,我需要你的帮助,下面的代码工作在95%左右,另外5%是问题。当我运行程序时,表单允许我选择我想要读取的文件,然后当我单击填充按钮(button2_Click_1)时,它会从那里下山。取消按钮不响应,标签不可见且不更新,进度条也是如此。我使用过Application.DoEvent,但我似乎仍无法让它工作。



  namespace  DellOrderUP 
{
public partial < span class =code-keyword> class Form1:Form
{
public Form1()
{
InitializeComponent();
}

// 一些公共变量
字符串文件名= ;

// 这是浏览按钮
私有 void button1_Click( object sender,EventArgs e)
{
// 流myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();

openFileDialog1.InitialDirectory = c:\\; // ***编辑:添加空格

openFileDialog1.Filter = < span class =code-string> txt files(* .xls)| * .xls |所有文件(*。*)| *。*;
openFileDialog1.FilterIndex = 2 ;
openFileDialog1.RestoreDirectory = true ;

if (openFileDialog1.ShowDialog()== DialogResult.OK)
{
// 向用户显示他们选择的文件。
// 他们只能通过浏览按钮更改它。
textBox1.Text = openFileDialog1.FileName;

// 将文件名传递给公共变量文件名
文件名= openFileDialog1.FileName;


// 检查扩展名
String Extension = openFileDialog1.FileName;

String Check = Path.GetExtension(Extension);
if (Check == 。xls || Check == 。xlsx || Check == 。xlsm
{
/ / 启用procced按钮
button2.Enabled = true ;
}
else
{
String 错误= 抱歉只有Excel文件!!!!;
字符串 caption = 仅限Excel < /跨度>;
MessageBox.Show(错误,标题);
button2.Enabled = false ;
}
}
}

// 私有void textBox1_TextChanged(object sender,EventArgs e)
// {}
private void textBox1_TextChanged( object sender,EventArgs e)
{}

// procceed
private void button2_Click_1( object sender,EventArgs e)
{
// 将文件路径传递给OpenExcelFile
OpenExcelFile(文件名);

// 使lable1可见并显示状态
label1。 Visible = true ;

// 进度条变得可见
progressBar1.Visible = true ;

}


// 关闭程序
private void button3_Click_1(对象 sender,EventArgs e)
{
string message = 是否要关闭此程序?;
string caption = InventoryUploader;
MessageBoxButtons button = MessageBoxButtons.YesNoCancel;

DialogResult结果;

result = MessageBox.Show( this ,message,caption,button);

if (result == DialogResult.Yes)
{
// 关闭父窗体。
this .Close();

}
}



private void label1_Click( object sender,EventArgs e)
{}
private void progressBar1_Click( object sender,EventArgs e)
{}


// 打开文件并读取数据中的颜色
private void OpenExcelFile( String filepath)
{

// 启用按钮3(取消按钮) )并禁用button2(已执行按钮)
button3.Enabled = true ;
button2.Enabled = false ;

Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(filepath);

Excel._Worksheet xlWorksheet = xlWorkbook.Sheets [ 1 ];

Excel.Range xlRange = xlWorksheet.UsedRange.Columns [ 37 ];

// 用户查看的更新状态
UpdateLabel ( 请等待,读取数据);


System.Array myvalues =(System.Array)xlRange.Cells.Value;
string [] strArray = myvalues.OfType< object>()。选择(o = > o.ToString())。ToArray();


// 获取strArray的大小
int Size_Of_strArray = strArray.Length;

// 创建一个新数组并使用前一个数组的大小初始化它
String [] FirstClean = new [Size_Of_strArray];
String [] SecondClean = new String < /跨度> [Size_Of_strArray];


// 用户查看的更新状态
UpdateLabel( 清理数据);


// 在这个循环中,单词(exec InsertDellInventory)将是从每个条目中删除
for int i = 1 ; i < Size_Of_strArray - 1 ; i ++)
{
FirstClean [i] = strArray [i]。删除( 0 24 );

// 现在删除''并将数据传递给第二个干净的数组
SecondClean [i] = FirstClean [i] .Replace( ' );
}

// 更新用户查看的进度
UpdateProgress( 10 );

// 将数组传递给插入函数
BeforeInsertingIntoDB( ref SecondClean);

}

// 更新进度条
private void UpdateProgress( int i)
{
progressBar1.Value = i;
this .progressBar1.Update();
Application.DoEvents();

} // 更新进度

// 更新标签
private void UpdateLabel( String status)
{
label1.Text = status
this .label1.Update();
Application.DoEvents();

} // 更新进度



private void BeforeInsertingIntoDB( ref string [] data)
{
// < span class =code-comment>更新状态供用户查看

UpdateLabel( 准备插入数据);


// 创建并初始化所有变量
字符串 PoNum = ; 字符串 OrderNum = ;

// 获取传递数组的大小
< span class =code-keyword> int
Size_Of_Array = data.Length;


for int i = 1 ; i < Size_Of_Array - 1 ; i ++)
{
字符串 Distribution = data [i];
counter = i; // 将i的值分配给计数器

String [] DistributionArray = Distribution.Split(' ,') ;

PoNum = DistributionArray [ 0 ]; OrderNum = DistributionArray [ 1 ];

// 调用InserDataintoDB函数
InsertDataIntoDB(PoNum, OrderNum)

}

// 调用更新进度函数
UpdateProgress( 40 );

} // End BeforeInsertingintoDB



// insertIntoDb
private void InsertDataIntoDB( String PoNum,字符串 OrderNum)

{

/// /更新用户状态以查看
UpdateLabel( 打开Db连接< /跨度>);

// 调用更新进度函数
UpdateProgress(< span class =code-digit> 20
);


字符串 InventoryUploader = ConfigurationManager.ConnectionStrings [ DellOrderUP.Properties.Settings.InventoryUploader]的ConnectionString。
SqlConnection con = new SqlConnection(InventoryUploader);

尝试
{
con.Open();

// 用户查看的更新状态
label1 .Text = 填充数据库;
this .label1.Update();

// 调用更新进度
UpdateProgress( 30 );


SqlCommand cmd = new SqlCommand( UploadDellOrder,con);
cmd.CommandType = CommandType.StoredProcedure;


cmd.Parameters.Add( new SqlParameter( @ ProdNum,SqlDbType.Int));
cmd.Parameters [ @ ProdNum]。Value = PoNum;

cmd.Parameters.Add( new SqlParameter( @ OrderNum,SqlDbType.Int));
cmd.Parameters [ @ OrderNum]。Value = OrderNum;


cmd.ExecuteNonQuery();

}
catch (例外e)
{
String caption_error_num = Convert.ToString(counter);
String error = e.ToString();
MessageBox.Show(error,caption_error_num);
}
最后
{
con.Close();
}

}





感谢您的帮助。



[edit]行中添加的空格 openFileDialog1.InitialDirectory =c:\\; 以避免scaped引号和格式colous中的混乱[/ edit]

解决方案

在button2_Click_1中你调用OpenExcelFile方法。



有几件事可能会出错。



首先,OpenExcelFile可能需要一些时间。甚至几秒钟(Excel自动化非常非常慢)。如果您希望应用程序始终响应,您应该将这些耗时的任务委托给单独的(非GUI)线程。



其次,OpenExcelFile可以生成错误数量(文件打开,文件不存在等)。你应该在那里提供一些错误处理来妥善处理这种情况。


hey guys pls I need your help, the code below works at about 95%, the other 5% is the problem. when I run the program,the form allows me to select the file I want to read and then when I click the populate button(button2_Click_1), it goes down hill from there. The cancel button does not respond, the label is not visible and doesn't update and the same goes for the progress bar. I have used Application.DoEvent, but I still can't seem to get it to work.

namespace DellOrderUP
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        // some public variables
        String Filename = "";

        // this is the browse button
        private void button1_Click(object sender, EventArgs e)
        {
            //Stream myStream = null;
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.InitialDirectory = "c:\\ ";  // *** Edit: Space added 

            openFileDialog1.Filter = "txt files (*.xls)|*.xls|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                // show the user the file they selected.
                // they can only change it through the browse button.
                textBox1.Text = openFileDialog1.FileName;

                // pass the filename to public variable filename
                Filename = openFileDialog1.FileName;


                //check extension
                String Extension = openFileDialog1.FileName;

                String Check = Path.GetExtension(Extension);
                if (Check == ".xls" || Check == ".xlsx" || Check == ".xlsm")
                {
                    // enable procced button
                    button2.Enabled = true;
                }
                else
                {
                    String Error = "Sorry Only Excel Files!!!!";
                    String caption = "Excel Only";
                    MessageBox.Show(Error, caption);
                    button2.Enabled = false;
                }
            }
        }

        //private void textBox1_TextChanged(object sender, EventArgs e)
        //{}
          private void textBox1_TextChanged(object sender, EventArgs e)
          {}

        // procceed
        private void button2_Click_1(object sender, EventArgs e)
        {
            // pass the file path to OpenExcelFile
            OpenExcelFile(Filename);

            // make lable1 visbible and show state
            label1.Visible = true;

            // progress bar becomes visible
            progressBar1.Visible = true;
            
        }


        // close the program
        private void button3_Click_1(object sender, EventArgs e)
        {
            string message = "Do you want to close this program ?";
            string caption = "InventoryUploader";
            MessageBoxButtons button = MessageBoxButtons.YesNoCancel;

            DialogResult result;

            result = MessageBox.Show(this, message, caption, button);

            if (result == DialogResult.Yes)
            {
                // Closes the parent form. 
                this.Close();

            }
        }



        private void label1_Click(object sender, EventArgs e)
        {}
        private void progressBar1_Click(object sender, EventArgs e)
        {}


        // opens the file and reads the coloumns of data in
        private void OpenExcelFile(String filepath)
        {

            // Enable button 3(cancel button) and disable button2(procced button)
            button3.Enabled = true;
            button2.Enabled = false;

            Excel.Application xlApp = new Excel.Application();
            Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(filepath);

            Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];

            Excel.Range xlRange = xlWorksheet.UsedRange.Columns[37];

            // update status for the user to see
            UpdateLabel("Please Wait, reading data");
            

            System.Array myvalues = (System.Array)xlRange.Cells.Value;
            string[] strArray = myvalues.OfType<object>().Select(o => o.ToString()).ToArray();


            // get the size of strArray
            int Size_Of_strArray = strArray.Length;

            // create a new array and initilize it with the size of the previous array
            String[] FirstClean = new String[Size_Of_strArray];
            String[] SecondClean = new String[Size_Of_strArray];


            // update status for the user to see
            UpdateLabel("Sanitizing data");
            

            // in this loop, the word (exec InsertDellInventory) will be removed from each entry
            for (int i = 1; i < Size_Of_strArray - 1; i++)
            {
                FirstClean[i] = strArray[i].Remove(0, 24);

                // now remove '' and pass the data to second clean array
                SecondClean[i] = FirstClean[i].Replace("'", "");
            }

            // update progress for the user to see
                UpdateProgress(10);

            // pass the array to insert function
            BeforeInsertingIntoDB(ref SecondClean);

        }

        // update the progress bar
        private void UpdateProgress( int i) 
        {
            progressBar1.Value = i;
            this.progressBar1.Update();
            Application.DoEvents();
      
        }// update the progress

        // update the label
        private void UpdateLabel( String status) 
        {
            label1.Text = status
            this.label1.Update();
            Application.DoEvents();
      
        }// update the progress



        private void BeforeInsertingIntoDB(ref string[] data)
        {
            //update status for the user to see
            UpdateLabel("Preparing data for insertion");
   

            // create and initialize all the variables
            String PoNum = ""; String OrderNum = "";

            // get the size of the passed array
            int Size_Of_Array = data.Length;


            for (int i = 1; i < Size_Of_Array - 1; i++)
            {
                String Distribution = data[i];
                counter = i; // assign the value of i to counter

                String[] DistributionArray = Distribution.Split(',');

                PoNum = DistributionArray[0]; OrderNum = DistributionArray[1]; 
                 
                 // call the InserDataintoDB functions
                 InsertDataIntoDB(PoNum, OrderNum)

            }

            // call the update progress function
            UpdateProgress(40);

        }// End BeforeInsertingintoDB



        // insertIntoDb
        private void InsertDataIntoDB(String PoNum, String OrderNum)

        {

            ////update status for the user to see
            UpdateLabel("Opening Db connection");
            
             // call the update progress function
            UpdateProgress(20);


            String InventoryUploader = ConfigurationManager.ConnectionStrings ["DellOrderUP.Properties.Settings.InventoryUploader"].ConnectionString;
            SqlConnection con = new SqlConnection(InventoryUploader);

            try
            {
                con.Open();

                //update status for the user to see
                label1.Text = "Populating Database";
                this.label1.Update();

                // call the update progress
                UpdateProgress(30);


                SqlCommand cmd = new SqlCommand("UploadDellOrder", con);
                cmd.CommandType = CommandType.StoredProcedure;


                cmd.Parameters.Add(new SqlParameter("@ProdNum", SqlDbType.Int));
                cmd.Parameters["@ProdNum"].Value = PoNum;

                cmd.Parameters.Add(new SqlParameter("@OrderNum", SqlDbType.Int));
                cmd.Parameters["@OrderNum"].Value = OrderNum;

                
                cmd.ExecuteNonQuery();

            }
            catch (Exception e)
            {
                String caption_error_num = Convert.ToString(counter);
                String error = e.ToString();
                MessageBox.Show(error,caption_error_num);
            }
            finally
            {
                con.Close();
            }

        }



Thanks for your help.

[edit] Space added in the line openFileDialog1.InitialDirectory = "c:\\"; to avoid scaped quotes and the mess in the formatting colous[/edit]

解决方案

Within button2_Click_1 you call OpenExcelFile method.

There are couple things that can go wrong there.

First, OpenExcelFile might take some time. Even several seconds (Excel Automation is very, very slow). If you want your application to be responsive all the time, you should delegate such time consuming tasks to the separate (non-GUI) thread.

Second, OpenExcelFile can produce number of errors (file aready open, file doesn't exist etc.). You should provide some error handling there to properly handle such cases.


这篇关于用户界面没有响应或更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆