Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 568
  • Last Modified:

Datagrid / DataList to create table with an "add record" input row (VB)

I have (or should say had) a datagrid (before I swapped it for a datalist) which is databound to a datasource.
I want to have the effect of a table containing a header, the rows of data and a single "add record" row with textboxes and an "add" button.
How do I do this or achieve the same effect?


I swapped over to a datalist with header/footers, thinking I could move my textbox inputs into the footer but the a) the code does not validate and b) the resulting output adds in additional <table> tags where I don't want them.
1 Solution
I use an SqlDataSource to databind a GridView to do this.

(1) Use a Union Query in the Select Command to provide a blank row.   Include a flag to identify this (which also helps with sorting).  

(2) Use the flag to determine if you need to insert or update in the UpdateCommand.

(2b) The InsertCommand is not used in this senario, it's all done by the UpdateCommand.  Simply use the Edit and Update CommandNames as for any other row.  I typically use the IsNewRow flag to select the appropriate image button URL and AlternateText.  It's handy if I need to do any extra formatting in the OnDataBound event to distinguish the row.

<asp:SqlDataSource ID=Sample runat=server
    ConnectionString='<%$ ConnectionStrings:YourConnectionString %>'
    SelectCommand="SELECT DataKey, DataValue, 0 As IsNewRow FROM KeyValues 
        UNION SELECT NULL As DataKey, NULL As DataValue, -1 As IsNewRow 
        ORDER BY IsNewRow, DataValue;"
    UpdateCommand="IF (@oldIsNewRow = -1) BEGIN
        INSERT INTO KeyValues (DataKey, DataValue) VALUES (@DataKey, @DataValue);
        UPDATE KeyValues SET DataKey=@DataKey, DataValue=@DataValue WHERE DataKey=@oldDataKey;
        <asp:Parameter Name=oldIsNewRow>
        <asp:Parameter Name=oldDataKey>
        <asp:Parameter Name=DataKey>
        <asp:Parameter Name=DataValue>

Open in new window


Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now