清空GridView

时间:2014-03-21 20:57:25

标签: c# asp.net

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

Specified argument was out of the range of valid values. Parameter name: index 

这个例外并不是一个非常难以诊断的例外。问题是,当DataSource为空时,如何清除GridView?

编辑:这是填充GridView

的完整功能
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
        }
    }

2 个答案:

答案 0 :(得分:0)

尝试gridView.Rows.Clear();它应该清除gridView,让你留下一个空的身体,但仍然有列标题。

答案 1 :(得分:0)

不是将数据源设置为null,而是创建新数据表并将数据源设置为该数据源。应该做的工作......