2013-07-31 49 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