Click here to Skip to main content
15,943,148 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi friends
The following is my code for generating datatable based on the rows and columns
DataTable result= userdao.getdateanddayfortimetable1(comp);
            DataTable  period = userdao.getperiodfortimetable();
            int periodcount = period.Rows.Count;
            int daycount = result.Rows.Count;
            //System.Windows.Forms.TableLayoutPanel panel = new System.Windows.Forms.TableLayoutPanel();
            //panel.Controls.Clear();
            //panel.ColumnStyles.Clear();
            //panel.RowStyles.Clear();
            //panel.ColumnCount = periodcount;
            //panel.RowCount = daycount;
            DataTable dt = new DataTable();
            for (int i = 0; i < daycount; i++)
            {
                dt.Rows.Add();
                for (int j = 0; j <periodcount; j++)
                {
                    dt.Columns.Add();
                }
            }
            
            //for (int k = 0; k < periodcount; k++)
            //{
            //    grid.Columns[k].HeaderText = period.Rows[k]["PeriodNo"].ToString(); //+"(" + period.Rows[k]["StartTime"].ToString() + period.Rows[k]["EndTime"].ToString() + ")";
            //}

            return dt;
            
        }



Here periodcount is the columnvalue and the daycount is the row value(for example periodcount=7 and daycount=4),but after executing for loop it return 4rows with 28 column for datatable.what's wrong with my code. help me to fix the problem.
Thank you
Posted
Comments
Richard C Bishop 23-Apr-13 10:24am    
Well 4 x 7 = 28. You are looping through periodcount 7 times for each daycount. Rethink your logic.

1 solution

Why are you adding rows and columns each time?
A table needs columns, which must be set once. So move your inner (columns) loop outside the outer (rows) loop.

You can then add the rows once you have added the columns:
C#
DataTable result = userdao.getdateanddayfortimetable1(comp);
DataTable period = userdao.getperiodfortimetable();
int periodcount = period.Rows.Count;
int daycount = result.Rows.Count;
DataTable dt = new DataTable();
for (int j = 0; j < periodcount; j++)
    {
    dt.Columns.Add();
    }
for (int i = 0; i < daycount; i++)
    {
    dt.Rows.Add();
    }
return dt;
 
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