如何显示DataTable返回的结果?

时间:2014-11-22 14:46:37

标签: asp.net sql-server data-binding

我的DataAccess类中有以下代码:

    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

如何显示DataTable产生的实际列和数据?

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分: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