Inserting new row in GridView in ASP.NET 2.0

The GridView was not designed to insert new rows, but there is a way to accomplish this with very little code.

  

  1. The first step is to add your data source and the DataView Grid. Ensure that your SqlDataSource statements or stored procedures in the:

    1. Select Command
    2. Insert Command
      1. My stored procedure just adds a new row and initializes to new or zero
    3. Update Command
    4. Delete Command

  2. Bind the DataView Grid to the SqlDataSource

  3. Edit the fields adding the following

    1. CommandField, enable the Edit and Delete, and disable the insert
    2. TemplateField



  4. In the UI source code, I inserted the Item Template as follows:
    1. <ItemTemplate>  
    2.   <asp:LinkButton ID="lblNew" runat="server" CausesValidation="false"  
    3.               CommandName="Insert"  
    4.               Text="New" style="vertical-align: middle; text-align:  
    5.               center" Font-Bold="False" ForeColor="Black"  
    6.               Height="3px" Width="49px"  
    7.     OnClick="GridViewInsert">  
    8.   </asp:LinkButton>  
    9. </ItemTemplate>
  5. Format the text as required, leaving the rest alone.

    1. Text="New" style="vertical-align: middle; text-align:   
    2. center" Font-Bold="False" ForeColor="Black"   
    3. Height="3px" Width="49px"

     

  6. Now your control looks as follows in design mode



  7. The next step is to add a few lines of code so that there is only one New, when the web page is running

  8. In the page where the control is running, insert the following code and change the names as required:

    1. protected void GridViewInsert(object sender, EventArgs e)  
    2. {  
    3.         SqlDataSource1.Insert();  
    4. }  
    5. protected void GridView1_PreRender(object sender, EventArgs e)  
    6. {  
    7.        for (int index = 0; index < GridView1.Rows.Count - 1; index++)  
    8.         {  
    9.   
    10.             GridView1.Rows[index].Cells[1].Controls[1].Visible = false;  
    11.         }  
    12. }

     

  9. Test and change the Cells[x] and Controls[x] as required

  10. There will be training for the users, the User Sequence is:

    1. The user presses the New button
      1. The stored procedure inserts New or zero into each field
    2. The user now sees a new row at the bottom with New
    3. The user edits this new row, changing the values as required.
    4. The user presses the Update

The user pressed the Edit button

The user entered data and pressed the Update button

So how did this work, well in step 4 above, the OnClick="GridViewInsert" above calls the GridViewInsert(object sender, EventArgs e) code and executes the SqlDataSource1.Insert();, which inserts the data. Getting rid of all of the News in the DataView (except for the last one), happened in the GridView1_PreRender code.


Similar Articles