将datagrid绑定到数据集

时间:2011-12-01 21:12:57

标签: asp.net datagrid

我试图将数据集指定为网格的源。所以,我就是这样做的:

        SqlCommand cmd = new SqlCommand("TEST",
                                               conn);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet d = new DataSet();
        da.Fill(d);
        grid2.DataSource = d;
        grid2.DataBind();

但是,我无法得到结果。网格在页面上不可见。可以解释让我知道这样做的方法吗?

1 个答案:

答案 0 :(得分:1)

您的代码不完整;但是,这是怎么做的:

//notice how the connection is enclosed in a using block
using (SqlConnection conn = new SqlConnection("ConnectionString"))
{
        conn.Open();//don't forget to open the connection
        SqlCommand cmd = new SqlCommand("TEST",conn);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet d = new DataSet();
        da.Fill(d);
        grid2.DataSource = d;
        grid2.DataBind();
}

顺便说一下,你不需要DataAdapter。你可以这样做:

//notice how the connection is enclosed in a using block
using (SqlConnection conn = new SqlConnection("ConnectionString"))
{
        conn.Open();//don't forget to open the connection
        SqlCommand cmd = new SqlCommand("TEST",conn);
        cmd.CommandType = CommandType.StoredProcedure;

        DataTable d = new DataTable();
        d.Load(cmd.ExecuteReader());
        grid2.DataSource = d;
        grid2.DataBind();
}