以前,我得到的建议是通过将GridView的DataSource设置为null并调用DataBind()来清除它。然而,当我这样做时,我会抛出一个异常:
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
}
}发布于 2014-03-22 05:08:30
试试gridView.Rows.Clear();它应该只清除gridView,留下一个空的正文,但列标题仍然在那里。
发布于 2014-03-22 05:10:15
与其将数据源设置为null,不如创建一个新的datatable并将其设置为null。应该能胜任这项工作。
https://stackoverflow.com/questions/22569405
复制相似问题