Существует лучший способ без необходимости повторного связывания Gridview
и принудительного вызова SqlDataSource
.
Использование ViewState
.
Когда вы загружаете Gridview, сохраняйте «данные» в переменную ViewState.
е
//ok let's load the gridview with data as normal and display it
//'sdsClasses' is the SQL data source
gvStudents.DataSourceID = "sdsClasses";
gvStudents.DataSource = null; // Null out the source, as we have a SourceID instead
gvStudents.DataBind(); //load the gridview and display it
//save the data in a viewstate for later use
DataView dvClasses = (DataView)sdsClasses.Select(DataSourceSelectArguments.Empty);
DataTable dt = new DataTable();
if (dv != null)
{
dt = dvClasses.ToTable();
ViewState["gv"] = dt;
}
Так что теперь, когда загружается Gridview, у вас есть данные, которые используются в памяти как ViewState.
Если вам нужно удалить строку, сделайте это ...
В моем примере я использую функцию поиска для поиска строки, которую я хочу удалить, основываясь на SelectValue из элемента управления dropdownlist. Вы должны будете использовать что-то подобное, чтобы точно указать строку, которую хотите удалить. Если вы хотите удалить последнюю строку, то делайте ForEach для DataTable построчно, пока не доберетесь до последней строки и не удалите!
//Load the dataview that was already saved in the ViewState
DataTable dt = (DataTable)ViewState["gv"];
//find the student in the datatable, row by row
bool found = false;
bool wsAtt = false; //flag to indicate if the student is already in the roll or not saved yet (ie: sdsClasses recordset)
foreach (DataRow dr in dt.Rows)
{
//compare studentID in the datatable with the selected value of the student to delete
//check that the field has TECNQ studentIDs otherwise use the 2nd cell in the row
if (dr[0].ToString().Contains("NQ"))
found = (found || dr[0].ToString() == ddlRemoveStudents.SelectedValue);
else
{
found = (found || dr[1].ToString() == ddlRemoveStudents.SelectedValue);
wsAtt = true;
}
//he should!
if (found)
{
//remove the row to the datatable
dt.Rows.Remove(dr);
//Bind the grid view to the datatable and refresh
gvStudents.DataSource = dt;
gvStudents.DataSourceID = null; // Null out the id, we have a source
gvStudents.DataBind();
//update the viewstate with the new amount of rows
ViewState["gv"] = dt;
}
}
Таким образом, вы можете видеть, используя ViewState в качестве замены SqlDataSource, вы можете манипулировать Gridview по своему усмотрению и никогда больше не вызывать исходный SqlDataSource, за исключением первого раза для получения данных.
И скажи своему профессору, что он высокомерный свинья.