2013-07-16 53 views
3

我正在C#窗口應用程序工作。我創建了一個窗體窗體,在那裏我添加了一個表格控件。在數據庫中我有一個表4列像書名,書籍圖像,書籍類別和書籍子類別。現在我有一個表中有10條記錄。如何動態添加表格佈局面板中的行和列

我想在表格面板中顯示所有這些數據。我嘗試了下面的代碼。但我沒有得到正確的輸出。我必須添加一個圖片框控件和三個標籤控件,即我必須創建4列,所以第1列將有圖片框,其他三列各有一個標籤。我嘗試的代碼給出了輸出,但不合適。它顯示了所有4列中的圖片框圖像,然後是標籤。

但我想顯示輸出像,每列應包含唯一的數據。

代碼:

public void DynamicGenerateTable(int columnCount, int rowCount) 
    { 
     tableLayoutPanel1.Controls.Clear(); 
     //Clear out the existing row and column styles 
     tableLayoutPanel1.ColumnStyles.Clear(); 
     tableLayoutPanel1.RowStyles.Clear(); 

     //Assign table no of rows and column 
     tableLayoutPanel1.ColumnCount = columnCount; 
     tableLayoutPanel1.RowCount = rowCount; 
     WiCommonFunction.LoadCommonSettings(); 
     ShowInformation show = new ShowInformation(); 
     //ds = show.ShowBookImage(); 
     ds1 = show.ShowBookCategory(); 
     DataTable dt1 = ds1.Tables[0]; 

     for (int i = 0; i < columnCount; i++) 
     { 
      tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize)); 

      for (int j = 0; j < rowCount; j++) 
      { 
       if (i == 0) 
       { 
        //defining the size of cell 
        tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize)); 
       } 
       PictureBox picture = new PictureBox(); 
       picture.Size = new Size(220, 180); 
       picture.SizeMode = PictureBoxSizeMode.StretchImage; 
       Byte[] byteImage = (Byte[])(dt1.Rows[j]["BookImage"]); 
       MemoryStream ms = new MemoryStream(byteImage); 
       picture.Image = Image.FromStream(ms); 

       Label lblCategory = new Label(); 
       lblCategory.Text = dt1.Rows[j]["CategoryName"].ToString(); 

       Label lblSubCategory = new Label(); 
       lblCategory.Text = dt1.Rows[j]["SubCategoryName"].ToString(); 

       Label lblBook = new Label(); 
       lblBook.Text = dt1.Rows[j]["BookName"].ToString(); 
       tableLayoutPanel1.Controls.Add(picture,i,j); 
       tableLayoutPanel1.Controls.Add(lblCategory, i, j); 
       tableLayoutPanel1.Controls.Add(lblSubCategory, i, j); 
       tableLayoutPanel1.Controls.Add(lblBook, i, j); 
      } 
     } 
    } 

請給我建議任何solution.Thanks提前。

回答

3

您將所有四個控件到您的每一個細胞,因爲你(I,J)的每個組合執行

  tableLayoutPanel1.Controls.Add(picture,i,j); 
      tableLayoutPanel1.Controls.Add(lblCategory, i, j); 
      tableLayoutPanel1.Controls.Add(lblSubCategory, i, j); 
      tableLayoutPanel1.Controls.Add(lblBook, i, j); 

。你需要一些switch語句來添加你想要添加到該單元格中的控件,如

 switch(i) { 
      case 0: 
      tableLayoutPanel1.Controls.Add(picture,i,j); 
      break; 
      case 1: 
      tableLayoutPanel1.Controls.Add(lblCategory, i, j); 
      break; 
      case 2: 
      tableLayoutPanel1.Controls.Add(lblSubCategory, i, j); 
      break; 
      case 3: 
      tableLayoutPanel1.Controls.Add(lblBook, i, j); 
      break; 
     } 
+0

thanks for reply.It幫助我,我得到了我想要的輸出 –