首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >清空GridView

清空GridView
EN

Stack Overflow用户
提问于 2014-03-22 04:57:25
回答 2查看 242关注 0票数 0

以前,我得到的建议是通过将GridView的DataSource设置为null并调用DataBind()来清除它。然而,当我这样做时,我会抛出一个异常:

代码语言:javascript
复制
Specified argument was out of the range of valid values. Parameter name: index 

这个异常并不是很难诊断的。问题是,当DataSource为空时,我如何清除我的GridView?

编辑:下面是填充GridView的完整函数

代码语言:javascript
复制
void PopulateGridView()
    {
        //Connect to database and get frames for selected job
        var dt = new DataTable();

        try
        {
            _connectionToDatabase.Open(); //open database

            var findDataCommand = new SqlCommand(SkidListSpName, _connectionToDatabase) { CommandType = CommandType.StoredProcedure };

            findDataCommand.Parameters.Add(new SqlParameter(SlParameter1, JobRelPhase_DropDown.SelectedValue));
            findDataCommand.Parameters.Add(new SqlParameter(SlParameter2, _stationId));

            var dataAdapter = new SqlDataAdapter(findDataCommand);
            dataAdapter.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                gridView.DataSource = dt;
                gridView.DataBind();
            }
            else
            {
                gridView.DataSource = null; //HERE is where I set the DataSource
                gridView.DataBind(); //removing this removes the exception
                StatusLabel.Text = "No items found.";
            }

            _connectionToDatabase.Close(); //close database
        }
        catch (Exception e)
        {
            StatusLabel.Text = "No items found.";
            TestLabel.Text = e.Message;
        }
        finally
        {
            _connectionToDatabase.Close(); //close database
        }
    }
EN

回答 2

Stack Overflow用户

发布于 2014-03-22 05:08:30

试试gridView.Rows.Clear();它应该只清除gridView,留下一个空的正文,但列标题仍然在那里。

票数 0
EN

Stack Overflow用户

发布于 2014-03-22 05:10:15

与其将数据源设置为null,不如创建一个新的datatable并将其设置为null。应该能胜任这项工作。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22569405

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档