![]() |
Web Development »
ASP.NET Controls »
General
Beginner
Adding a row to an ASP.NET DataGridBy balazs_hideghetyThis article describes an easy and elegant way of inserting a row into a DataGrid. |
C#, Windows, .NET, ASP.NET, Visual Studio, Dev
|
|
Advanced Search |
|
|
|
||||||||||||||||

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.
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).
SqlConnection to it.
DataGrid and an insert button. I've also added an edit/update/cancel button column to the DataGrid.
DataGrid and implementing the insert.
DataGrid.OnItemCommand event. OnItemCommand event � here we write the execution code for the Insert, Update, Edit and Cancel commands.
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
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)
{
// inserting
grid.EditItemIndex = 0;
// modify text
EditCommandColumn ecc =
(EditCommandColumn) grid.Columns[0];
ecc.UpdateText = "Insert";
// fill table, insert empty row, bind to datagrid
Fill();
InsertEmpty();
Bind();
}
private void grid_ItemCommand(object source,
System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
// stop editing
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":
// begin editing
grid.EditItemIndex = e.Item.ItemIndex;
break;
}
// fill and bind
Fill();
Bind();
}
I know it�s not much, but I hope it helps you out.
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 14 Jul 2005 Editor: Rinish Biju |
Copyright 2005 by balazs_hideghety Everything else Copyright © CodeProject, 1999-2009 Web17 | Advertise on the Code Project |