Click here to Skip to main content
Email Password   helpLost your password?

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.

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
Generaluse SqlDataReader?
evanssthomas
3:42 27 Oct '09  
Hi, Is there a way to accomplish the same using SqlDataReader (instead of DataAdapter) ?
Generaltrapping the Insert Event
Member 2553299
2:13 4 Jul '08  
Hi... my problem is, I could completely work the code out for me, but when I click on "Insert", I am not able to get any event so that I could write my db command to insert that data into the database!! dont know where I am going wrong.
GeneralCast Specified valid exception
Member 2553299
1:02 3 Jul '08  
On the following statement I am getting Cast Specified not Valid exception.

EditCommandColumn ecc = (EditCommandColumn)grid.Columns[0];

any idea why is it happening ?

regards
GeneralRe: Cast Specified valid exception
Member 2553299
2:14 4 Jul '08  
I was able to resolve. The mistake I was doing was, I had the edit in column 7 whereas I was putting 0. You have forgive me for my ignorance.
Generalinsert into 2 tables at the same time
lailah
23:43 7 Sep '07  
first of all, thank you so much for the tutorial Smile

and please if you wouldn't mind, could you explain how to insert a record into 2 tables?
GeneralRe: insert into 2 tables at the same time
balazs_hideghety
23:44 15 Sep '07  
please be more specific. 2 tables on the DB leel or inserting rows to two tables on the GUI level?

a) in the GUI (grid) you can have data's from more than one table. inserting and reading works the same way as here. after finishing editing, you have to open a db connection, create a transaction and insert the rows to the 1st then to the 2nd table, then do a commit)

b) if you have 2 grids on the asp.net form, i think it's possible to put the 2 grids into editing phase, although the 2 grids will for sure work separated...

hope this will help you.


C#, ASPX, SQL, novice to NHibernate

Generalhow do you read the inserted cells ?
ytb1000
23:28 20 Aug '07  
I can't seem to bring any data back from the inserted cells .. in the grid_itemcommand section

GeneralRe: how do you read the inserted cells ?
balazs_hideghety
6:09 21 Aug '07  
just like you read the values of any cells you're updating.
you have to reference the TextBox components used to enter the data, and use the Text property.

C#, ASPX, SQL, novice to NHibernate

GeneralIts working, but
Elavarasu
2:58 19 Jun '06  
It is working fine, but i am unable to insert the data into my database as well as unable to update and delete

can u give me the full solution for that

Elavarasu
GeneralInsert vs Update
DarKhan
10:26 28 Nov '05  
Even with the change of the EditCommandColumn UpdateText to Insert, e.CommandName in the grid_ItemsCommand method still resolves as "Update", not "Insert".

Any ideas on a way to distinguish between the two?

Thanks in advance,

Scott
GeneralRe: Insert vs Update
DarKhan
11:00 28 Nov '05  
To fix this issue evaluate the text of the LinkButton. Switch the code in the switch box to ((LinkButton)e.CommandSource).Text.ToString().
GeneralRe: Insert vs Update
abhiace
19:48 16 Mar '06  
I tried using (LinkButton)e.CommandSource).Text in the switch statement of
the ItemCommand event handler but I'm still getting the Text as "Update" and not "Insert".
My guess is that since the Page is constructed on each request to the server,the change to the text which was made in the Add button event handler is not perisisted across Postbacks, any suggestions/thoughts?
GeneralRe: Insert vs Update
Bruce E
7:52 6 Oct '06  
Yes there is a defect in the switch statement. I am using PushButton and not the LinkButton. Here is what I had to do to get the Switch to work correctly

//switch (e.CommandName)
switch (((System.Web.UI.WebControls.Button)e.CommandSource).Text)
{

case "Insert":
//Get the new string from the textbox
string newInsTxt = ((TextBox)e.Item.Cells[1].Controls[0]).Text;
//Do the insert
Insert(newInsTxt);
break;

case "Cancel":
EditCommandColumn ecc = (EditCommandColumn) StatusDataGrid.Columns[0];
ecc.UpdateText = "Update";
break;.......

The addButton_Click method set the text of the button on the DataGrid to "Insert" so without the switch looking at the button text correctly, it would never hit the Insert case.

Now the only issue is that that I get two postBack's in the case statement.


Bruce Ellis
Generalto VB code
Yang79
2:36 16 Sep '05  
How to change this to VB code? Any idea? Because I having problem in casting EditCommandColumn to grid.columns(0)
GeneralRe: to VB code
Anonymous
7:43 19 Sep '05  
Sorry, have too little VB.NET experience...have you tried:
Dim o as Object
Set o = grid.columns(0) as EditCommandColumn

By the way, what's the exception or what kind of error do you get?
GeneralChanging Font
waycool66
12:05 15 Aug '05  
Nice article and a elegant solution. Is there a way to font/font size for the editing/inserting cells ? they don't match with the rest of the grid.
GeneralRe: Changing Font
balazs_hideghety
2:16 16 Aug '05  
you can set the style of the grid through css classes, but the template columns contains textbox (or may contain any other) controls. for them you need to set the css class separately.

<b>Just examine the HTML below:</b>
<asp:TemplateColumn HeaderText="Any text for header">
     <HeaderStyle Width="52px"></HeaderStyle>
     <ItemTemplate>
          <asp:RadioButton id=rbA CSSCLASS = "anyCSSClass" Text='<%# DataBinder.Eval(Container.DataItem, "pristup") %>' Runat="server" GroupName="P">
          </asp:RadioButton>
     </ItemTemplate>
     <EditItemTemplate>
          <asp:RadioButton id=rbEditA Text='<%# DataBinder.Eval(Container.DataItem, "pristup") %>' Runat="server" GroupName="G">
          </asp:RadioButton>
     </EditItemTemplate>
</asp:TemplateColumn>

C#, ASPX, COM, SQL
GeneralRe: Changing Font
waycool66
4:44 16 Aug '05  
what I meant was is there a way to change font of the text box in your code (for the edit/insert cells) at the run time ? I don't think you were using template column, right ?
Generalchange font ?
waycool66
12:03 15 Aug '05  
Very good article and elegant solution. One question though: Can I change font or font size in the edit cells/insert cells ? It seems they don't match Css I set for the Grid.
GeneralRe: change font ?
Member 2553299
1:00 3 Jul '08  
On the following statement I am getting Cast Specified not Valid exception.

EditCommandColumn ecc = (EditCommandColumn)grid.Columns[0];

any idea why is it happening ?

regards


Last Updated 14 Jul 2005 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010