Empty a GridView
本文关键字:GridView Empty | 更新日期: 2023-09-27 17:51:14
以前,我被建议通过将其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
}
}
尝试gridView.Rows.Clear();它应该只是清除gridView,留下一个空的主体,但列标题仍然在那里。
与其将数据源设置为null,不如创建一个新的数据表并将数据源设置为null。