// this event fires prior to all of the other commands
// use it to provide a more graceful transition out of edit mode
CheckIsEditing(e.CommandName);
}
void CheckIsEditing(string commandName) {
if (DataGrid1.EditItemIndex != -1) {
// we are currently editing a row
if (commandName != "Cancel" && commandName != "Update") {
// user's edit changes (if any) will not be committed
Message.Text = "Your changes have not been saved yet. Please press update to save your changes, or cancel to discard your changes, before selecting another item.";
isEditing = true;
}
}
}
// get the edit text boxes
string id = ((TextBox)e.Item.Cells[2].Controls[0]).Text;
string lname = ((TextBox)e.Item.Cells[3].Controls[0]).Text;
string fname = ((TextBox)e.Item.Cells[4].Controls[0]).Text;
// TODO: update the Command value for your application
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlCommand UpdateCommand = new SqlCommand();
UpdateCommand.Connection = myConnection;
if (AddingNew)
UpdateCommand.CommandText = "INSERT INTO authors(au_id, au_lname, au_fname, contract) VALUES (@au_id, @au_lname, @au_fname, 0)";
else
UpdateCommand.CommandText = "UPDATE authors SET au_lname = @au_lname, au_fname = @au_fname WHERE au_id = @au_id";
// the key value for this row is in the DataKeys collection
string keyValue = (string)DataGrid1.DataKeys[e.Item.ItemIndex];
// TODO: update the Command value for your application
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlCommand DeleteCommand = new SqlCommand("DELETE from authors where au_id='" + keyValue + "'", myConnection);
// execute the command
myConnection.Open();
DeleteCommand.ExecuteNonQuery();
myConnection.Close();
// add a new row to the end of the data, and set editing mode 'on'
CheckIsEditing("");
if (!isEditing) {
// set the flag so we know to do an insert at Update time
AddingNew = true;
// add new row to the end of the dataset after binding
// first get the data
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter myCommand = new SqlDataAdapter(SelectCommand, myConnection);
DataSet ds = new DataSet();
myCommand.Fill(ds);
// add a new blank row to the end of the data
object[] rowValues = { "", "", "" };
ds.Tables[0].Rows.Add(rowValues);
// figure out the EditItemIndex, last record on last page
int recordCount = ds.Tables[0].Rows.Count;
if (recordCount > 1)
recordCount--;
DataGrid1.CurrentPageIndex = recordCount/DataGrid1.PageSize;
DataGrid1.EditItemIndex = recordCount%DataGrid1.PageSize;