The GridView was not designed to insert new rows, but there is a way to accomplish this with very little code.
- The first step is to add your data source and the DataView Grid. Ensure that your SqlDataSource statements or stored procedures in the:
- Select Command
- Insert Command
- My stored procedure just adds a new row and initializes to new or zero
- Update Command
- Delete Command
- Bind the DataView Grid to the SqlDataSource
- Edit the fields adding the following
- CommandField, enable the Edit and Delete, and disable the insert
- TemplateField
- In the UI source code, I inserted the Item Template as follows:
- <ItemTemplate>
- <asp:LinkButton ID="lblNew" runat="server" CausesValidation="false"
- CommandName="Insert"
- Text="New" style="vertical-align: middle; text-align:
- center" Font-Bold="False" ForeColor="Black"
- Height="3px" Width="49px"
- OnClick="GridViewInsert">
- </asp:LinkButton>
- </ItemTemplate>
-
Format the text as required, leaving the rest alone.
- Text="New" style="vertical-align: middle; text-align:
- center" Font-Bold="False" ForeColor="Black"
- Height="3px" Width="49px"
-
Now your control looks as follows in design mode
-
The next step is to add a few lines of code so that there is only one New, when the web page is running
-
In the page where the control is running, insert the following code and change the names as required:
- protected void GridViewInsert(object sender, EventArgs e)
- {
- SqlDataSource1.Insert();
- }
- protected void GridView1_PreRender(object sender, EventArgs e)
- {
- for (int index = 0; index < GridView1.Rows.Count - 1; index++)
- {
-
- GridView1.Rows[index].Cells[1].Controls[1].Visible = false;
- }
- }
-
Test and change the Cells[x] and Controls[x] as required
-
There will be training for the users, the User Sequence is:
- The user presses the New button
- The stored procedure inserts New or zero into each field
- The user now sees a new row at the bottom with New
- The user edits this new row, changing the values as required.
- 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.