5,446,823 members and growing! (18,638 online)
Email Password   helpLost your password?
Web Development » ASP.NET Controls » General     Beginner

Adding a row to an ASP.NET DataGrid

By balazs_hideghety

This article describes an easy and elegant way of inserting a row into a DataGrid.
C#, Windows, .NET, Visual Studio, ASP.NET, Dev

Posted: 14 Jul 2005
Updated: 14 Jul 2005
Views: 90,371
Bookmarked: 40 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
15 votes for this Article.
Popularity: 4.00 Rating: 3.40 out of 5
4 votes, 26.7%
1
0 votes, 0.0%
2
1 vote, 6.7%
3
5 votes, 33.3%
4
5 votes, 33.3%
5

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

  1. I've created a simple web project and added SqlConnection to it.
  2. Added a DataGrid and an insert button. I've also added an edit/update/cancel button column to the DataGrid.
  3. Created code for populating the DataGrid and implementing the insert.
    1. function for filling,
    2. function for inserting an empty row to the DataSource,
    3. function for binding the new table to the grid.
    4. and finally I have added the delegate for the DataGrid.OnItemCommand event.

Actually only two things are needed

  1. To handle the OnItemCommand event – here we write the execution code for the Insert, Update, Edit and Cancel commands.
  2. 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)
{
    // 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();
}

Conclusion

I know it’s not much, but I hope it helps you out.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

balazs_hideghety


Since 1999 I work in IT. Worked 2-3 yrs with Borland Builder C++. Since .NET appeared, I program in C#, ASP.NET.

You may know the current technologies, but still there's a lot of experience to gain. IT's evolving all the time.

From 2006 I'm a MCP. Now I'm focusing on technologies like: NHibernate, NSpring...
Occupation: Web Developer
Location: Slovakia Slovakia

Other popular ASP.NET Controls articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 19 of 19 (Total in Forum: 19) (Refresh)FirstPrevNext
Subject  Author Date 
Generaltrapping the Insert EventmemberMember 25532992:13 4 Jul '08  
GeneralCast Specified valid exceptionmemberMember 25532991:02 3 Jul '08  
GeneralRe: Cast Specified valid exceptionmemberMember 25532992:14 4 Jul '08  
Generalinsert into 2 tables at the same timememberlailah23:43 7 Sep '07  
GeneralRe: insert into 2 tables at the same timememberbalazs_hideghety23:44 15 Sep '07  
Generalhow do you read the inserted cells ?memberytb100023:28 20 Aug '07  
GeneralRe: how do you read the inserted cells ?memberbalazs_hideghety6:09 21 Aug '07  
GeneralIts working, butmemberElavarasu2:58 19 Jun '06  
GeneralInsert vs UpdatememberDarKhan10:26 28 Nov '05  
GeneralRe: Insert vs UpdatememberDarKhan11:00 28 Nov '05  
GeneralRe: Insert vs Updatememberabhiace19:48 16 Mar '06  
GeneralRe: Insert vs UpdatememberBruce E7:52 6 Oct '06  
Generalto VB codememberYang792:36 16 Sep '05  
GeneralRe: to VB codesussAnonymous7:43 19 Sep '05  
GeneralChanging Fontsusswaycool6612:05 15 Aug '05  
GeneralRe: Changing Fontmemberbalazs_hideghety2:16 16 Aug '05  
GeneralRe: Changing Fontsusswaycool664:44 16 Aug '05  
Generalchange font ?susswaycool6612:03 15 Aug '05  
GeneralRe: change font ?memberMember 25532991:00 3 Jul '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 14 Jul 2005
Editor: Rinish Biju
Copyright 2005 by balazs_hideghety
Everything else Copyright © CodeProject, 1999-2008
Web13 | Advertise on the Code Project