<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html><head>
<title>Editing Data in a DataGrid Control</title>
</head>
<body bgcolor="#ffffff">
<span class="heading">Editing Data in a DataGrid Control</span><hr />
void Page_Load(Object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindDataGrid(); // create data set and bind to grid control
}
void DoItemEdit(Object objSource, DataGridCommandEventArgs objArgs)
{
// set the EditItemIndex property of the grid to this item's index
MyDataGrid.EditItemIndex = objArgs.Item.ItemIndex;
BindDataGrid(); // bind the data and display it
}
void DoItemUpdate(Object objSource, DataGridCommandEventArgs objArgs)
{
// get a reference to the title and publication date text boxes
TextBox objTitleCtrl = (TextBox)objArgs.Item.FindControl("txtTitle");
TextBox objPubDateCtrl = (TextBox)objArgs.Item.Cells[2].Controls[0];
// create a suitable SQL statement and execute it
string strSQL = "UPDATE Booklist SET Title='" + objTitleCtrl.Text + "', "
+ "PublicationDate='" + objPubDateCtrl.Text + "' "
+ "WHERE ISBN='" + MyDataGrid.DataKeys[objArgs.Item.ItemIndex] + "'";
ExecuteSQLStatement(strSQL);
// set EditItemIndex property of grid to -1 to switch out of Edit mode
MyDataGrid.EditItemIndex = -1;
BindDataGrid(); // bind the data and display it
}
void DoItemCancel(Object objSource, DataGridCommandEventArgs objArgs)
{
// set EditItemIndex property of grid to -1 to switch out of Edit mode
MyDataGrid.EditItemIndex = -1;
BindDataGrid(); // bind the data and display it
}
void BindDataGrid()
{
// get connection string from web.config
string strConnect = ConfigurationSettings.AppSettings["DsnWroxBooksOleDb"];
// create a SQL statement to select some rows from the database
string strSelect = "SELECT * FROM BookList WHERE ISBN LIKE '%07645437%'";
// create a variable to hold an instance of a DataReader object
OleDbDataReader objDataReader;
try
{
// create a new Connection object using the connection string
OleDbConnection objConnect = new OleDbConnection(strConnect);
// open the connection to the database
objConnect.Open();
// create a new Command using the connection object and select statement
OleDbCommand objCommand = new OleDbCommand(strSelect, objConnect);
// execute the SQL statement against the command to get the DataReader
objDataReader = objCommand.ExecuteReader();
}
catch (Exception objError)
{
// display error details
outError.InnerHtml = "<b>* Error while accessing data</b>.<br />"
+ objError.Message + "<br />" + objError.Source + "<p />";
return; // and stop execution
}
// set the DataSource property and bind the grid
MyDataGrid.DataSource = objDataReader;
MyDataGrid.DataBind();
}