Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
hi,all my friends!

I am a new coder!
I must learn C++ and C# by myself as soon as possible!


Recently,I revise a C# program.
There is a DataGridView in the program.
Run program,Display of the DataGridView is normal。
But it is dead or no-response when i click or move scrollBar.
I don't know why.
Please help!

1/28,I found that maybe is backgroundWorker1.RunWorkerAsync() problem!


code:
C#
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    Int32 TimeFrom, TimeTo;
    ClearGraph();
    /* Clear all list */
    _lstLine.Clear();
    //_lstRestore.Clear();

    _lstRestore._errors.Clear();
    _lstRestore._happentime.Clear();
    _lstRestore._line.Clear();
    _lstRestore._process.Clear();

    lblUpdateTime.Visible = false;

    if (cbTimeFrom.Text == "" || cbTimeTo.Text == "")
    {
        //MessageBox.Show("Nhap thoi gian can tim vao di");
        MessageBox.Show("Select Start and End time");
    }
    else if (cbProcess.Text == "")
        MessageBox.Show("Select Process");//Nhap cong doan can tim kiem vao di
    if (cboMain.Text == "")//cboMain.Text==null
        MessageBox.Show("Select Floor");//Chon Main can tim vao di
    else
    {
        TimeFrom = Convert.ToInt32(cbTimeFrom.Text);
        TimeTo = Convert.ToInt32(cbTimeTo.Text);
        DateTime DateFrom = new DateTime(dtpDateFrom.Value.Year, dtpDateFrom.Value.Month, dtpDateFrom.Value.Day, TimeFrom, 0, 0);
        DateTime DateTo = new DateTime(dtpDateTo.Value.Year, dtpDateTo.Value.Month, dtpDateTo.Value.Day, TimeTo, 59, 59);
        MySqlConnection connection = new MySqlConnection(MyConnectionString);
        try
        {
            connection.Open();
            //db=new DataClassesDataContext(strConnectionString);
        }
        catch (Exception ex)
        {
            MessageBox.Show("Connected to Database errors!: " + ex.Message);
        }

        tblRobotMonitoring temp_lstRestore = new tblRobotMonitoring();
        temp_lstRestore._happentime = new List<DateTime>();
        temp_lstRestore._errors = new List<string>();
        temp_lstRestore._line = new List<string>();
        temp_lstRestore._process = new List<string>();

        MySqlCommand cmd = connection.CreateCommand();
        cmd.CommandText = "set names utf8";
        cmd.ExecuteNonQuery();

        cmd.CommandText = "select HappenTime,Errors,Line,Process from tblRobotMonitoring where HappenTime >= @Time1 and HappenTime<=@Time2";
        cmd.Parameters.Add(new MySqlParameter("@Time1", MySqlDbType.DateTime, 0));
        cmd.Parameters.Add(new MySqlParameter("@Time2", MySqlDbType.DateTime, 0));

        cmd.Parameters["@Time1"].Value = DateFrom;
        cmd.Parameters["@Time2"].Value = DateTo;

        MySqlDataReader rd = cmd.ExecuteReader();
        while (rd.Read())
        {
            DateTime temp_happentime = new DateTime();
            DateTime.TryParse(rd[0].ToString(), out temp_happentime);

            _lstRestore._happentime.Add(temp_happentime);
            _lstRestore._errors.Add(rd[1].ToString());
            _lstRestore._line.Add(rd[2].ToString());
            _lstRestore._process.Add(rd[3].ToString());
        }
        rd.Close();
        cmd.Parameters.Clear();

        connection.Close();

        if (_lstRestore._line.Count() <= 0)
        {

            MessageBox.Show("No Data !");
            lblResult.Text = "Fail SUM : " + _lstRestore._line.Count().ToString();
            lblMainAveResult.Text = "No Data";
            lblResult.Visible = true;

            _lstRestore._errors.Clear();
            _lstRestore._happentime.Clear();
            _lstRestore._line.Clear();
            _lstRestore._process.Clear();

            return;
        }
        else
        {
            lblResult.Visible = true;
            foreach (string va in _lstRestore._line)
            {
                //Add cac line da input du lieu vao he thong
                if (!_lstLine.Contains(va))
                    _lstLine.Add(va);
            }

            var Dictionarys = new Dictionary<string, int>(_lstLine.Count());
            foreach (string line in _lstLine)
            {
                int count = 0;
                foreach (string va in _lstRestore._line)
                {
                    if (va.Equals(line)) ++count;
                }
                //var RecordLine = from tbl in items where (tbl.Line.Equals(line)) select tbl;
                Dictionarys.Add(line, count);
            }
            var take = (from tbl in Dictionarys orderby tbl.Value descending select tbl).Take(100);
            List<string> listLine = new List<string>();
            List<Double> listLineValue = new List<double>();

            foreach (var pair in take)
            {
                listLine.Add(pair.Key);
                listLineValue.Add((double)pair.Value);
            }
            /*  Loc cac loai loi xay ra tren tat ca cac line va hien thi tren data grid view */
            List<string> _lstError = new List<string>();
            List<string> _lstFilteredError = new List<string>();
            /* add cac loi vao list */
            foreach (var va in _lstRestore._errors)
            {
                // if (!_lstError.Contains(va.Errors))
                _lstError.Add(va);
            }
            //hoan thanh 40% cong viec:
            backgroundWorker1.ReportProgress(40);
            /* Clear data grid view */
            dgv1.DataSource = null;
            dgv1.Rows.Clear();
            /* Filter cac loi */
            for (int i = 0; i < _lstError.Count(); i++)
            {
                //them vao progress bar
                int per =40+ 60 *i/ _lstError.Count();
                backgroundWorker1.ReportProgress(per);
                for (int j = 0; j < _lstError.Count(); j++)
                {
                    if (StringCompare(_lstError[i], _lstError[j]))
                    {
                        _lstError[i] = sResult;
                        _lstError[j] = sResult;
                    }

                }
                if (!_lstFilteredError.Contains(sResult))
                    _lstFilteredError.Add(sResult);
            }
            lblResult.Text = "Fail SUM: " + _lstRestore._line.Count().ToString();
            _lstLine = listLine;
            ShowGraph so = new ShowGraph(zg1, "Fail", "Line", "Count", listLine, listLineValue, "Bar");
            foreach (string error in _lstFilteredError)
            {
                var RecordError = from tbl in _lstError where tbl.Equals(error) select tbl;

                dgv1.Rows.Add(error, RecordError.Count());
            }
            dgv1.Refresh();

            lblMainAveResult.Text = (_lstRestore._line.Count() / _lstLine.Count()).ToString();
        }
        /*connection.Close();*/
    }
}
Posted
Updated 27-Jan-14 13:26pm
v3
Comments
Ganesh KP 26-Jan-14 23:58pm    
Please post some more code to make us understand @wang.
aolin.wang 27-Jan-14 0:35am    
I already update my question!
Sergey Alexandrovich Kryukov 27-Jan-14 19:37pm    
You are right, it looks like a background worker problem. You mistake is pretty apparent — please see my answer.
—SA
aolin.wang 27-Jan-14 20:32pm    
hi,I found this codes.
CheckForIllegalCrossThreadCalls = false;
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker2.WorkerReportsProgress = true;
and
private void btnSearch_Click(object sender, EventArgs e)
{
//RetrieveData();//

progressBar1.Visible = true;
progressBar1.Value = 0;
chkUpdate.Checked = false;
if (!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync();
}

}
BR!
Sergey Alexandrovich Kryukov 27-Jan-14 20:47pm    
Listen carefully: Never ever do CheckForIllegalCrossThreadCalls = false;! Never. This is very serious thing.
(And of course, never use code sample you don't understand completely. Are you a software developer or who?)

I gave you a complete solution, please use it. This is the only way to survive multithreading code with UI.

—SA

1 solution

You did not show how your method backgroundWorker1_DoWork is invoked, but its name (never use auto-generated names!) suggests that this is a method executed by your background worker in a separate thread, not a UI thread. And then first lines show what you do wrong. Take, for example, the call to МessageBox.Show.

You cannot call anything related to UI from non-UI thread. Instead, you need to use the method Invoke or BeginInvoke of System.Windows.Threading.Dispatcher (for both Forms or WPF) or System.Windows.Forms.Control (Forms only).

You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].

See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net[^],
Control events not firing after enable disable + multithreading[^].

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900