2014-11-22 76 views
1

我在我的数据访问类下面的代码:如何显示DataTable返回的结果?

public IEnumerable<Object> getAllPersons() 
    { 
     string CommandText = "Select * from Person"; 
     SqlCommand oCommand = new SqlCommand(CommandText, oConnection); 
     oCommand.CommandType = CommandType.Text; 

     // Create a datatable and SqlDataAdapter 
     SqlDataAdapter oAdapter = new SqlDataAdapter(); 
     oAdapter.SelectCommand = oCommand; 
     DataTable oDataTable = new DataTable(); 
     try 
     { 
      // Open Connection and fill the datatable using the SqlDataAdapter 
      oConnection.Open(); 
      oAdapter.Fill(oDataTable); 
      return oDataTable.AsEnumerable(); 
     } 
     catch (Exception oException) 
     { 
      throw oException; 
     } 
     finally 
     { 
      // Close the SqlConnection 
      oConnection.Close(); 
     } 
    } 

在我的表现层我需要绑定这个返回的DataTable到我的网格,这是我的代码:

 DataAccess mydataaccess = new DataAccess(); 
     IEnumerable<object> personList=mydataaccess .getAllPersons(); 

     GridView1.DataSource = personList; 
     GridView1.DataBind(); 

这将导致以下:

enter image description here

如何显示实际列和数据起因于大taTable?

+0

你是如何设法编译这段代码的? – Steve 2014-11-22 14:50:42

+0

你是什么意思? – user3340627 2014-11-22 14:52:06

+1

@Steve,我想我明白你的意思,我的代码中有一个缺失的部分,请检查编辑后的代码 – user3340627 2014-11-22 14:53:05

回答

0

的网格失败,则该IEnumerable<object>到数据源绑定。
您需要将您的DataRow序列转换为可分配给DataSource属性的对象。

你可以改变你GetPerson方法你为什么不返回一个IEnumerble<DataRow>不是通用对象

public IEnumerable<DataRow> getAllPersons() 

DataAccess mydataaccess = new DataAccess(); 
IEnumerable<DataRow> personList=mydataaccess .getAllPersons(); 

GridView1.DataSource = personList.CopyToDataTable(); 
GridView1.DataBind(); 

但在这一点上,我想知道的,并在绑定呼叫直接从你的getAllPersons方法中返回一个DataTable

0

更改您的代码如下。您可以更轻松地绑定到DataTable而不是IEnumerable。

public DataTable getAllPersons() 
{ 
    string CommandText = "Select * from Person"; 
    SqlCommand oCommand = new SqlCommand(CommandText, oConnection); 
    oCommand.CommandType = CommandType.Text; 

    // Create a datatable and SqlDataAdapter 
    SqlDataAdapter oAdapter = new SqlDataAdapter(); 
    oAdapter.SelectCommand = oCommand; 
    DataTable oDataTable = new DataTable(); 
    try 
    { 
     // Open Connection and fill the datatable using the SqlDataAdapter 
     oConnection.Open(); 
     oAdapter.Fill(oDataTable); 
    } 
    catch (Exception oException) 
    { 
     throw oException; 
    } 
    finally 
    { 
     // Close the SqlConnection 
     oConnection.Close(); 
    } 
    return oDataTable; 
} 

在您的aspx文件中添加以下属性。

<asp:GridView ID="GridView1" Runat="server" AutoGenerateColumns="true" /> 

这将显示您的对象中的每一列,因此你最有可能想要像下面的东西。

<asp:GridView ID="productGridView" Runat="server" 
     <Columns> 
      <asp:BoundField HeaderText="Colum Name A" DataField="ColumNameA"> 
      </asp:BoundField> 
      <asp:BoundField HeaderText="Colum Name B" DataField="ColumNameB"> 
      </asp:BoundField> 
     </Columns> 
</asp:GridView> 
+0

我在aspx中得到了这个,但它没有帮助 – user3340627 2014-11-22 15:00:42