Data Controls 101
I’ve worked with asp.net a bit at school before I came to Microsoft. Being the “data dev” as you would imagine, I get lots of bugs that have to do with the data (datasource/databound) controls. I also scan the internal and external forums and try to help customers find solutions to their problems. This blog post is the first of a series on common scenarios using data controls, that I call Data Controls 101.
When new developers come to asp.net from other web technologies/backgrounds the tendency is to continue doing things as they did before, when in fact they should learn the paradigms we expect in asp.net webforms (mvc is kind of different).
These posts will be scenario driven with tidbits of information here and there. Let’s start with a simplest case:
I want to show a list of categories from my database.
Before you pick a control and rush to go write code, you should ask other questions that will help narrow the choices down. Do I want to delete, update, insert, select? Do I want to define my control template manually or use column auto generation? After you decide what set of functionality you want there is still probably a bunch combinations of controls you want choose to accomplish your goal.
Controls |
Select |
Delete |
Inline Edit |
Insert |
Paging |
Sorting |
Column Autogeneration |
GridView |
x |
x |
x |
- |
x |
x |
x |
ListView |
x |
x |
x |
x |
x (DataPager) |
x |
- |
Repeater |
- |
- |
- |
- |
- |
- |
- |
DetailsView |
- |
x |
x |
x |
x |
- |
x |
FormView |
- |
x |
x |
x |
x |
- |
- |
DataList |
x |
x |
x |
- |
- |
- |
- |
The above table is a summary of what those controls on the left support out of the box without much added effort (some other controls can do the same thing with a little more work).
Ok so we’ve decided to we want a tabular layout, paging, sorting and selection with inline editing. Looking at the table I’d pick the GridView or ListView.
Next goal is to choose the datasource control. The same kinds of questions apply when picking the datasource control, but it is more specific to how you want to access your data. In my case I’ll use LinqDataSource.
Finally the code:
<asp:LinqDataSource ID="categoriesSource"
EnableUpdate="true"
runat="server"
ContextTypeName="FowlerSample.NorthwindDataContext"
TableName="Categories">
</asp:LinqDataSource>
<asp:GridView ID="categories"
runat="server"
AllowPaging="True"
AllowSorting="True"
DataKeyNames="CategoryID"
DataSourceID="categoriesSource">
<Columns>
<asp:CommandField ShowSelectButton="True" ShowEditButton="true" />
</Columns>
</asp:GridView>
That’s all you have to write and suddenly things just work. Next time I'll go over some of how the “magic” works.