2013-07-31 52 views
0

是否可以基於列表創建gridview?我有以下列表:基於列表的可編輯gridview

ID = 1 
Name = John 
Zip = 33141 
ID = 2 
Name = Tim 
Zip = 33139 

我希望能夠創建一個可編輯的GridView與此列表

當我把它綁定到網格視圖,它似乎把everyting在一列中,我無法弄清楚如何得到它把它單獨成不同的列

這裏是我的設置GridViewDataSource代碼:

DataTable table = ConvertListToDataTable(personList); 
GridView1.DataSource = table; 
GridView1.DataBind(); 

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

    // Get max columns. 
    int columns = 7; 

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

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

    return table; 
} 

回答

0

下面是一個例子:

private class Person 
    { 
     int m_iID; 
     string m_sName; 
     string m_sZip; 

     public int ID { get { return m_iID; } } 
     public string Name { get { return m_sName; } } 
     public string Zip { get { return m_sZip; } } 

     public Person(int iID, string sName, string sZip) 
     { 
      m_iID = iID; 
      m_sName = sName; 
      m_sZip = sZip; 
     } 
    } 

    private List<Person> m_People; 

    private void ConvertListToDataTable(List<Person> People) 
    { 
     DataTable table = new DataTable(); 

     DataColumn col1 = new DataColumn("ID"); 
     DataColumn col2 = new DataColumn("Name"); 
     DataColumn col3 = new DataColumn("Zip"); 

     col1.DataType = System.Type.GetType("System.String"); 
     col2.DataType = System.Type.GetType("System.String"); 
     col3.DataType = System.Type.GetType("System.String"); 

     table.Columns.Add(col1); 
     table.Columns.Add(col2); 
     table.Columns.Add(col3); 


     foreach (Person person in People) 
     { 
      DataRow row = table.NewRow(); 
      row[col1] = person.ID; 
      row[col2] = person.Name; 
      row[col3] = person.Zip; 

      table.Rows.Add(row); 
     }    

     GridView1.DataSource = table; 
     GridView1.DataBind(); 
    } 
+0

很棒的例子,非常感謝。 – user2593590

+0

我將如何在單獨的類文件中創建Person類,並且能夠在我的代碼中爲表單使用它? – user2593590

+0

添加新項目 - >代碼 - >類。然後創建/移動Person類到它。在文件後面的表單代碼中,使用「使用ProjectNamespace.Folder」類文件。例如,如果您的類文件位於您的App_Code文件夾中:使用ProjectNamespace.App_Code; 。確保選擇這個答案,如果它回答你的問題! – Mausimo