2013-10-08 55 views
0

我需要從數據表中創建一個objectdatasource。我現在有一個方法,即生成datatble:將數據錶轉換爲objectdatasource

static DataTable GetTableForDropDown() 
    { 

     DataTable dt = new DataTable(); 
     DataRow dr = null; 
     dt.Columns.Add(new DataColumn("DurationType", typeof(string))); 

     dr = dt.NewRow(); 
     dr["DurationType"] = "Hours"; 
     dt.Rows.Add(dr); 

     dr = dt.NewRow(); 
     dr["DurationType"] = "Days"; 
     dt.Rows.Add(dr); 

     dr = dt.NewRow(); 
     dr["DurationType"] = "Weeks"; 
     dt.Rows.Add(dr); 

     dr = dt.NewRow(); 
     dr["DurationType"] = "Months"; 
     dt.Rows.Add(dr); 
     return dt; 
    } 

,我需要創建和ObjectDataSource並將其加載到它。我發現很少的文件或如何做到這一點。我發現下面的代碼嘗試轉換它,但是當我嘗試它時,它只會引發錯誤。

var edgeDataSource = new ObjectDataSource(
      "MyNamespace.MyClass, MyNamespace.MyClasss, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce8ab85a8f42a5e8", 
      "GetTableForDropDown") {ID = "EdgeDataSource"}; 

回答

1

什麼,你可以嘗試是這樣的(我把它放在一個文件只是爲了簡單)

namespace MyNamespace 
{ 
    public class MyClassData 
    { 
     public string DurationType { get; set; } 
    } 

    public class MyClass 
    { 
     public List<MyClassData> GetTableForDropDown() 
     { 
      List<MyClassData> myList = new List<MyClassData>(); 
      myList.Add(new MyClassData { DurationType = "Hours" }); 
      myList.Add(new MyClassData { DurationType = "Days" }); 
      myList.Add(new MyClassData { DurationType = "Weeks" }); 
      myList.Add(new MyClassData { DurationType = "Month" }); 
      return myList; 
     } 
    } 

    public partial class WebForm18 : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 
      var edgeDataSource = new ObjectDataSource("MyNamespace.MyClass", "GetTableForDropDown"); 
      var x = edgeDataSource.Select(); 
     } 
    } 
}