Hello,

i have created Calender for a year and i m checking the existance of each day in database and filling color accodingly.Also in my calender i can make "sunday or sturday" to normal day.My form if gettting hang.

So i have used thread to load the calender but still i m not able to run my form .

Please help me , if anyone knows the solution.
Below is my code.

private void Calendar_Load(object sender, EventArgs e)
        {
  this.Cursor = Cursors.WaitCursor;
           thread = new Thread(new ThreadStart(LoadCurrentCalender));
            thread.Start();
}
  private void LoadCurrentCalender()
        {
            
            int CurrentYear = Convert.ToInt32(nud_year.Value);
            dgv_calendar.Rows.Clear();
            for (int i = 1; i <= 12; i++)
            {          
                DateTime tempdate = new DateTime(CurrentYear, i,15);
                int daysinmonth = DateTime.DaysInMonth(CurrentYear, i);
                int startcoulmnindex = 0,endcoulmnindex=0;
                #region SET START AND END COULMNINDEX
                switch (tempdate.DayOfWeek)
                {
                    case DayOfWeek.Monday:
                        startcoulmnindex = 0; endcoulmnindex = daysinmonth;
                        break;
                    case DayOfWeek.Tuesday:
                        startcoulmnindex = 1; endcoulmnindex = daysinmonth + 1;
                        break;
                    case DayOfWeek.Wednesday:
                        startcoulmnindex = 2; endcoulmnindex = daysinmonth + 2;
                        break;
                    case DayOfWeek.Thursday:
                        startcoulmnindex = 3; endcoulmnindex = daysinmonth + 3;
                        break;
                    case DayOfWeek.Friday:
                        startcoulmnindex = 4; endcoulmnindex = daysinmonth +4;
                        break;
                    case DayOfWeek.Saturday:
                        startcoulmnindex = 5; endcoulmnindex = daysinmonth +5;
                        break;
                    case DayOfWeek.Sunday:
                        startcoulmnindex = 6; endcoulmnindex = daysinmonth + 6;
                        break;
                }
                #endregion
                int currentrowindex=i-1;
                DataGridViewRow dgrow = new DataGridViewRow();
                if (dgv_calendar.InvokeRequired)
                {
                    dgv_calendar.Invoke(new StatusPanelDelegate(LoadCurrentCalender));
                }
                dgv_calendar.Rows.Insert(currentrowindex, dgrow);
                dgv_calendar.Rows[currentrowindex].HeaderCell.Value = tempdate.ToString("MMMM");
                int temp = 0;
                for (int j = startcoulmnindex; j < endcoulmnindex; j++)
                {
                    #region DATEVALUE
                    temp++;
                    DateTime datevalu=new DateTime(CurrentYear, i,temp);
                    dgv_calendar.Rows[currentrowindex].Cells[j].Value = datevalu.Date;
                    #endregion
                    #region CHECK FOR EXISTINGCALENDER DATE
                    int dayid = 0;
                    BL_Calendar db = new BL_Calendar(Connstring);
                    db.changeddate = datevalu;
                    SqlDataReader reader = db.CheckExistingCalenderDateandGetValue();
                    if (reader != null)
                    {
                        if (reader.HasRows)
                        {
                            if (reader.Read())
                            {
                                dayid = Convert.ToInt32(reader["dayid"]);
                            }
                        }
                    }
                    #endregion
                    #region FOR NORMAL DAYS
                    if (dgv_calendar.Columns[j].HeaderText == "M" || dgv_calendar.Columns[j].HeaderText == "T" || dgv_calendar.Columns[j].HeaderText == "W" || dgv_calendar.Columns[j].HeaderText == "T" || dgv_calendar.Columns[j].HeaderText == "F")
                    {                     
                        if (dayid == 0)
                        {
                            dgv_calendar.Rows[currentrowindex].Cells[j].Style.BackColor = Color.LightGreen;
                            dgv_calendar.Rows[currentrowindex].Cells[j].Style.ForeColor = Color.LightGreen;
                        }
                        else
                        {
                            db.dayid = dayid;
                            db.action = "filter";
                            SqlDataReader dr = db.GetDayColor();
                            if (dr != null)
                            {
                                if (dr.Read())
                                {
                                    dgv_calendar.Rows[currentrowindex].Cells[j].Style.BackColor = Color.FromName(Convert.ToString(dr["colorcode"]));
                                    dgv_calendar.Rows[currentrowindex].Cells[j].Style.ForeColor = dgv_calendar.Rows[currentrowindex].Cells[j].Style.BackColor;
                                }
                            }
                        }
                    }
                    #endregion
                    #region FOR SATURDAY AND SUNDAy
                    else if (dgv_calendar.Columns[j].HeaderText == "S")
                    {
                        if (dgv_calendar.Columns[j].Name == "SUN1" || dgv_calendar.Columns[j].Name == "SUN2" || dgv_calendar.Columns[j].Name == "SUN3" || dgv_calendar.Columns[j].Name == "SUN4" || dgv_calendar.Columns[j].Name == "SUN5")
                        {
                            if (dayid == 0)
                            {
                                dgv_calendar.Rows[currentrowindex].Cells[j].Style.BackColor = Color.Pink;
                                dgv_calendar.Rows[currentrowindex].Cells[j].Style.ForeColor = Color.Pink;
                            }
                            else
                            {
                                db.dayid = dayid;
                                db.action = "filter";
                                SqlDataReader dr = db.GetDayColor();
                                if (dr != null)
                                {
                                    if (dr.Read())
                                    {
                                        dgv_calendar.Rows[currentrowindex].Cells[j].Style.BackColor = Color.FromName(Convert.ToString(dr["colorcode"]));
                                        dgv_calendar.Rows[currentrowindex].Cells[j].Style.ForeColor = dgv_calendar.Rows[currentrowindex].Cells[j].Style.BackColor;
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (dayid == 0)
                            {
                                dgv_calendar.Rows[currentrowindex].Cells[j].Style.BackColor = Color.LightBlue;
                                dgv_calendar.Rows[currentrowindex].Cells[j].Style.ForeColor = Color.LightBlue;
                            }
                            else
                            {
                                db.dayid = dayid;
                                db.action = "filter";
                                SqlDataReader dr = db.GetDayColor();
                                if (dr != null)
                                {
                                    if (dr.Read())
                                    {
                                        dgv_calendar.Rows[currentrowindex].Cells[j].Style.BackColor = Color.FromName(Convert.ToString(dr["colorcode"]));
                                        dgv_calendar.Rows[currentrowindex].Cells[j].Style.ForeColor = dgv_calendar.Rows[currentrowindex].Cells[j].Style.BackColor;
                                    }
                                }
                            }
                        }
                    }
                    #endregion
                }
            }
            dgv_calendar.Rows[0].Cells[0].Selected = false;
            thread.Abort();
        }

Dani AI

Generated

Likely cause: the background thread is invoking the entire LoadCurrentCalender back onto the UI thread, so the heavy work runs on the UI thread and the form appears to hang. That also explains why single‑stepping in the debugger makes it look fine — stepping changes timing and can hide this kind of synchronous handover. , the Invoke call should only be used to perform small UI updates, not to re-run the whole worker method. was right to ask about where it blocks; the check-and-Invoke inside the loop is the smoking gun.

Fix checklist (practical, in order):

  • Read control values (for example nud_year.Value) on the UI thread before starting background work and store them in local variables.
  • Do all heavy CPU and DB work on a background thread and build a plain data model (DataTable, List<simple DTO>, dictionary of date->dayid/color) there. Avoid creating UI objects on the background thread.
  • Update the UI only with small, marshalled actions: either assign a completed DataTable to DataGridView.DataSource in one UI call, or use BeginInvoke/Invoke to perform tiny UI operations (create rows/cells on the UI thread).
  • Stop using Thread.Abort(); let the worker return or use a cancellation token.
  • Reduce DB round trips: SELECT all calendar rows for the year once and SELECT all color mappings once; cache them in dictionaries and use lookups.

Example pattern (modern, safe):

private async void Calendar_Load(object sender, EventArgs e)
{
    Cursor = Cursors.WaitCursor;
    int year = (int)nud_year.Value; // capture on UI thread

    var table = await Task.Run(() => BuildCalendarTable(year)); // all DB work here

    dgv_calendar.DataSource = table; // single UI assignment
    Cursor = Cursors.Default;
}

Notes and cautions:

  • Don’t call Invoke to execute the same worker method on the UI thread — that defeats background threading.
  • If you must update the grid incrementally, prepare simple data entries on the background thread and create/insert the actual DataGridViewRow inside a BeginInvoke action.
  • Profile DB queries first; creating a DB reader per date is slow. Fetch ranges and color mappings in bulk and join them in memory.

Recommended Answers

All 3 Replies

Please Help i am stuck here from 3 days.

Thanks

Where exactly is it hanging? Have you run the code in the debugger and looked at the values of the variables? Have you single stepped through the code to see what was happening?

Hello,
Yes i have debug the code.Code is not throwing exception.
if i Debug the code step by step.it is running properly.
But when i run the form without debugger .the form gets hang.
Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.