【问题标题】:bind datagrid to dataset将数据网格绑定到数据集
【发布时间】:2011-12-01 21:12:56
【问题描述】:

我一直在尝试将数据集分配为网格的源。所以,这就是我所做的:

        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();

但是,我无法得到结果。网格在页面上不可见。可以请教一下方法吗?

【问题讨论】:

    标签: asp.net datagrid


    【解决方案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();
    }
    

    【讨论】:

    • 我一直在做同样的事情,但它不工作
    • @Nishanth:那么你的 proc 没有返回任何数据。
    • 是的,我的 proc 运行良好。为了测试它,我只写了一个 select * 语句
    • @Nishanth:当你执行你的代码时,它会抛出任何异常吗?你看过连接字符串吗?它是否指向正确的数据库等?同样,我发布的代码绝对正确。设置断点并调试应用程序。
    • 它不会抛出任何异常
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 2016-11-13
    • 1970-01-01
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    • 2011-01-31
    相关资源
    最近更新 更多