
Introduction
I was searching for a way to insert new rows into a DataGrid on a web page. There were lots of useful and useless links on the web, but neither of them was elegant enough. It is important to have an easy to understand and a good organized code. So here’s my solution for the problem.
Why use this solution
You don't need to create a separate dialog box (window) for adding an item to the table. Also, you can use the same logic (and code) for verifying the inserted data and the modified data (the data that’s about to be updated).
The solution
What I have done
- I've created a simple web project and added
SqlConnection to it.
- Added a
DataGrid and an insert button. I've also added an edit/update/cancel button column to the DataGrid.
- Created code for populating the
DataGrid and implementing the insert.
- function for filling,
- function for inserting an empty row to the DataSource,
- function for binding the new table to the grid.
- and finally I have added the delegate for the
DataGrid.OnItemCommand event.
Actually only two things are needed
- To handle the
OnItemCommand event – here we write the execution code for the Insert, Update, Edit and Cancel commands.
- To do the inserting – we have to write the function for the button insert delegate – this piece of code is also responsible for changing the Update text to Insert (see the Edit/Update/Cancel button column).
The code
private void Page_Load(object sender, System.EventArgs e)
{
if (! IsPostBack)
{
Fill();
Bind();
}
}
private void Fill()
{
table = new DataTable();
SqlDataAdapter adapter =
new SqlDataAdapter("select * from t_CPredvolba", conn);
adapter.Fill(table);
}
private void Bind()
{
grid.DataSource = table;
grid.DataBind();
}
private void InsertEmpty()
{
table.Rows.InsertAt(table.NewRow(), 0);
}
private void add_Click(object sender, System.EventArgs e)
{
grid.EditItemIndex = 0;
EditCommandColumn ecc =
(EditCommandColumn) grid.Columns[0];
ecc.UpdateText = "Insert";
Fill();
InsertEmpty();
Bind();
}
private void grid_ItemCommand(object source,
System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
grid.EditItemIndex = -1;
switch (e.CommandName)
{
case "Insert":
break;
case "Update":
break;
case "Cancel":
EditCommandColumn ecc =
(EditCommandColumn) grid.Columns[0];
ecc.UpdateText = "Update";
break;
case "Edit":
grid.EditItemIndex = e.Item.ItemIndex;
break;
}
Fill();
Bind();
}
Conclusion
I know it’s not much, but I hope it helps you out.