ASP.Net Code

ASP.Net 2.0 – Populate and Edit Data in a Gridview Control

Back in the days of ASP, it meant hours of work to display the content of a database table on a web page. Then if you want to edit the data, that's almost a full day's work. But if you wanted to get fancy and add sorting and paging, well that's a couple more days right there! But now with ASP.Net 2.0, and the advent of the GridView control, it's approximately 15 minutes of work, and about the same number of lines of code! Here's the code to have a fully operational web page that displays data, pages, sorts, and modifies it.
I've also added in the code to overwrite the defult 'edit', 'cancel', and 'update' text with icons.


<asp:GridView ID="GridCountries" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataSourceID="DSCountries" DataKeyNames="id" CssClass="GridView" BorderWidth="0px">
            <Columns>
                <asp:BoundField ItemStyle-HorizontalAlign="Left" ControlStyle-CssClass="text" DataField="name" HeaderText="name" SortExpression="name" />
                <asp:BoundField ControlStyle-CssClass="text" DataField="code" HeaderText="code" SortExpression="code" />
                <asp:CommandField ShowEditButton="True" EditImageUrl="~/images/icons/edit.gif" UpdateImageUrl="~/images/icons/save.gif" CancelImageUrl="~/images/icons/undo.gif" ButtonType="Image" >
                </asp:CommandField>
             </Columns>
            <HeaderStyle CssClass="HeaderRow" />
            <AlternatingRowStyle CssClass="OddRow" />
            <EditRowStyle CssClass="EditRow" />
        </asp:GridView>
        <asp:SqlDataSource ID="DSCountries" runat="server" 
            ConnectionString="<%$ ConnectionStrings:ConnString %>"
            SelectCommand="SELECT id, name, code FROM countries ORDER BY name" 
            UpdateCommand="UPDATE countries SET name=@name, code=@code WHERE id=@id"/>
Share

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image