C# 如果datatable有列但没有行,gridview数据绑定将失败

C# 如果datatable有列但没有行,gridview数据绑定将失败,c#,asp.net,gridview,data-binding,dataset,C#,Asp.net,Gridview,Data Binding,Dataset,我正在将包含多个数据表的动态数据集返回到动态生成的网格视图。我使用下面的代码分别对每个数据表进行数据绑定 // Create the grid views for each one that was returned foreach (System.Data.DataTable table in datset.Tables) { WebCommon.Controls.GridView view = new WebCommon.Control

我正在将包含多个数据表的动态数据集返回到动态生成的网格视图。我使用下面的代码分别对每个数据表进行数据绑定

// Create the grid views for each one that was returned
        foreach (System.Data.DataTable table in datset.Tables)
        {
            WebCommon.Controls.GridView view = new WebCommon.Controls.GridView();
            ReportContainerPanel.Controls.Add(view);
            view.AutoGenerateColumns = true;
            view.ShowHeaderWhenEmpty = true;
            view.ShowHeader = true;
            view.ID = table.TableName;
            view.Size = WebCommon.Enums.TableSize.Small;
            view.DataSource = table;
            view.DataBind();

            // Add the spacer
            Literal spacer = new Literal();
            spacer.Text = "<br/>";
            ReportContainerPanel.Controls.Add(spacer);
        }
但是,如果返回的datatable有列,但有0行,则会出现此异常

id为“Table4”的GridView的数据源没有用于生成列的任何属性或属性。确保您的数据源包含内容

我知道我可以通过检查行数,然后将该行排除在打印之外来防止这种情况发生,但是用户可以看到没有为网格返回任何数据。因此,我希望显示一个带有标题列的空网格。有办法避免这个错误吗


编辑这个问题实际上似乎是因为有问题的空结果只有一列varbinary类型,而gridview根本不喜欢这样

只需检查是否有空集

如果集合为空,请添加一个空行,然后继续

    foreach (System.Data.DataTable table in datset.Tables)
    {
        if(table.Rows.Count == 0)
        {
            <code to add a new row>
        }//at this point the rest of the operations should work on the table

        WebCommon.Controls.GridView view = new WebCommon.Controls.GridView();
        ReportContainerPanel.Controls.Add(view);
        view.AutoGenerateColumns = true;
        view.ShowHeaderWhenEmpty = true;
        view.ShowHeader = true;
        view.ID = table.TableName;
        view.Size = WebCommon.Enums.TableSize.Small;
        view.DataSource = table;
        view.DataBind();

        // Add the spacer
        Literal spacer = new Literal();
        spacer.Text = "<br/>";
        ReportContainerPanel.Controls.Add(spacer);
    }

我明确地说我不想跳过空集。我希望它们仍然作为空表显示给用户。我是否需要手动从数据表中提取信息并自己构建gridview?@ChrisRice抱歉,我已经编辑了我的回复。如果有一个空集,则添加一个空行,这将导致数据集出现,并且可以避免错误,因为datatable在该点上有一行。