2014-04-03 136 views
1

我有一個類的列表,我想在datagridview中顯示它。綁定列表到DataGridView

這是我的代碼,但它不顯示列表:

public partial class Configuration : UserControl 
{ 
    TestInfoClass liste = new TestInfoClass(); 

    public Configuration() 
    { 
     InitializeComponent(); 

     datagridview_Items.DataSource = liste; // here not work, not show anything   
    } 
} 

主要形式有:?

public partial class MainForm : Form 
{ 
    Configuration list_to_dgv = new Configuration(); 
    TestInfoClass testInfo = null; 
    //code... 
    Configuration list_to_dgv = new Configuration(); 
} 

回答

0

我不知道什麼是您的回報功能,所以我做的例如我自己的例子。 返回列表中的函數應該是這樣的:

public DataSet ShowUsers() 
    { 
     DataSet op = new DataSet(); 
     SqlConnection objconnection = new SqlConnection(obj.strconnection()); 
     SqlCommand objcommand = new SqlCommand(); 
     DataSet objdataset = new DataSet(); 
     SqlDataAdapter objdataadapter = new SqlDataAdapter(); 
     objdataadapter.SelectCommand = objcommand; 
     objdataadapter.SelectCommand.Connection = objconnection; 
     objdataadapter.SelectCommand.CommandType = CommandType.StoredProcedure; 
     objdataadapter.SelectCommand.CommandText = "ShowUsers"; 
     objdataadapter.Fill(objdataset, "sheet"); 
     return objdataset; 
    } 

而且在你的表格,你應該有一些這樣的事:

​​

所以我認爲你應該添加數據成員和因爲它不起作用。

如果你在你的類對象的列表,你應該在列表轉換爲這樣的表:

List<string[]> list = new List<string[]>(); 
     list.Add(new string[] { "Column 1", "Column 2", "Column 3" }); 
     list.Add(new string[] { "Row 2", "Row 2" }); 
     list.Add(new string[] { "Row 3" }); 

     // Convert to DataTable. 
     DataTable table = ConvertListToDataTable(list); 
     dataGridView1.DataSource = table; 

轉換功能:

static DataTable ConvertListToDataTable(List<string[]> list) 
    { 
     // New table. 
     DataTable table = new DataTable(); 

     // Get max columns. 
     int columns = 0; 
     foreach (var array in list) 
     { 
     if (array.Length > columns) 
     { 
      columns = array.Length; 
     } 
     } 

     // Add columns. 
     for (int i = 0; i < columns; i++) 
     { 
     table.Columns.Add(); 
     } 

     // Add rows. 
     foreach (var array in list) 
     { 
     table.Rows.Add(array); 
     } 

     return table; 
    } 
+0

如何?我沒有選擇製作dataBind ... 謝謝 – user3345868

+0

它是c#應用程序?還是web表單應用程序? –

+0

windowform in c# – user3345868