【问题标题】:gridview databind fails if datatable has columns but no rows如果数据表有列但没有行,gridview 数据绑定失败
【发布时间】:2014-10-15 09:56:46
【问题描述】:

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

// 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);
        }

但如果返回的数据表有列但有 0 行,我会收到此异常。

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

我知道我可以通过检查行数然后排除该行数来防止这种情况被打印,但是对于用户来说看到没有为网格返回数据很有用。所以我想要一个带有标题列的空网格来显示。有没有办法解决这个错误?

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

【问题讨论】:

    标签: c# asp.net gridview data-binding dataset


    【解决方案1】:

    只检查一个空集,

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

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

    How to create a new row for a dataset

    【讨论】:

    • 我特别说过我不想跳过空集。我希望它们仍然向用户显示为空表。我是否需要手动从数据表中提取信息并自己构建gridview?
    • @ChrisRice 抱歉,我已经编辑了我的回复。如果您有一个空集,则添加一个空白行(这将导致数据集出现),您将避免错误,因为数据表在该点有一行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-16
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多