1

I am in the process of creating an asp.net web app in C# using Visual Studio. I have a registration page whereby children can register, their details are then sent to a 'children' table in my database, and upon clicking a 'view registered children' button, a new page opens which displays the first name, DOB and username(pk) of every child registered. As things stand, the DOB are stored and read as '04/02/2006'. I now need to find a way to get an age from the DOB and to be able to view the children by age groups (6-10, 11-13, 14-16).

I was wondering what the simplest way to achieve this would be? Radio buttons for each age group, that when selected, show only the children from that age group in the gridview. Or maybe when the page is loaded and all the children are shown on the gridview, they're already sorted into age groups?

Could someone advise me on the easiest way to achieve this, bearing in mind that I am new to C# & asp.net! I've attached screenshots of how my gridview currently looks. Thanks in advance.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;

namespace Coursework
{
public partial class Testy1 : System.Web.UI.Page
{
    //create a datasource
    SqlDataSource source = new SqlDataSource();

    protected void Page_Load(object sender, EventArgs e)
    {
        //always set some defaults for the sqldatasource
        source.ID = "source1";
        SqlConnection connectionString = new SqlConnection(ConfigurationManager.ConnectionStrings["newregDBConnectionString"].ConnectionString);
        source.SelectCommand = "SELECT firstname, dob, DATEDIFF(hour, dob, GETDATE()) / 8766 AS age FROM table ORDER BY age";

        if (!IsPostBack)
        {
            //bind the grid
            GridView1.DataSource = source;
            GridView1.DataBind();
        }
    }

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        //the new database query, now with where clause
        source.SelectCommand = "SELECT firstname, dob, DATEDIFF(hour, dob, GETDATE()) / 8766 AS age FROM table WHERE (DATEDIFF(hour, dob, GETDATE()) / 8766 BETWEEN @start AND @end) ORDER BY age";

        //get the end age from the dropdown and cast as int
        int end = Convert.ToInt32(DropDownList1.SelectedValue);

        //get the start int for the filter
        int start = end - 5;

        //if the filter is resetted, make sure the query returns all ages
        if (end == 0)
        {
            start = 0;
            end = 99;
        }

        //replace the parameters in the query
        source.SelectParameters.Add("start", start.ToString());
        source.SelectParameters.Add("end", end.ToString());

        //rebind the grid
        GridView1.DataSource = source;
        GridView1.DataBind();
    }
}

}

Latest look

ACostea
  • 141
  • 2
  • 18
  • 2
    Sort your data source for the grid. – mybirthname Dec 12 '16 at 13:00
  • Can you elaborate? I have never used gridviews before and am completely new to .net and c#! – ACostea Dec 12 '16 at 13:29
  • how do you get your data into the GridView ? do you [bind it to the `DataSource`](https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.datasource(v=vs.110).aspx)? or do you do it manually – Mong Zhu Dec 12 '16 at 13:37
  • So you should make your dob column clickable, on click you hit(go) to your controller with specific attribute sortByDate ="ASC" or sortByDate="Desc" depending on your case. When you are in your, I suppose index controller, and you receive this parameter sortByDate, you should query the data with .OrderByDescending or OrderBy this date. This if you are using mvc. If you are using asp.net forms the approach is the same but you need to rebind your DataGrid with correct sorted data on the button click. – mybirthname Dec 12 '16 at 13:37
  • I have binded it to the data source. I will try this approach, I am using asp.net forms though, so how do I go about rebinding datagrid with correct sorted data on button click? – ACostea Dec 12 '16 at 13:45

1 Answers1

2

You can start with this snippet. The first thing you need to do is edit your query of getting data from the database. Add the following: DATEDIFF(hour, dob, GETDATE()) / 8766 as AGE, this will give you the age of the people in your database. You can then use it to filter by age.

Then add a DropDownList to the page with an OnSelectedIndexChanged event and AutoPostback set to true.

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
    <asp:ListItem Text="Filter age" Value="0"></asp:ListItem>
    <asp:ListItem Text="0 - 5" Value="5"></asp:ListItem>
    <asp:ListItem Text="6 - 10" Value="10"></asp:ListItem>
    <asp:ListItem Text="10 - 15" Value="15"></asp:ListItem>
</asp:DropDownList>


<asp:GridView ID="GridView1" runat="server">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <%# Eval("firstname") %>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <ItemTemplate>
                <%# Convert.ToDateTime(Eval("dob")).ToString("d MMMM yyyy") %>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <ItemTemplate>
                <%# Eval("age") %>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

And then in code behind

using System;
......

namespace Project1
{
    public partial class WebForm1: System.Web.UI.Page
    {
        //create a datasource
        SqlDataSource source = new SqlDataSource();

        protected void Page_Load(object sender, EventArgs e)
        {
            //always set some defaults for the sqldatasource
            source.ID = "source1";
            source.ConnectionString = "connectionString";
            source.SelectCommand = "SELECT firstname, dob, DATEDIFF(hour, dob, GETDATE()) / 8766 AS age FROM table ORDER BY age";

            if (!IsPostBack)
            {
                //bind the grid
                GridView1.DataSource = source;
                GridView1.DataBind();
            }
        }

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //the new database query, now with where clause
            source.SelectCommand = "SELECT firstname, dob, DATEDIFF(hour, dob, GETDATE()) / 8766 AS age FROM table WHERE (DATEDIFF(hour, dob, GETDATE()) / 8766 BETWEEN @start AND @end) ORDER BY age";

            //get the end age from the dropdown and cast as int
            int end = Convert.ToInt32(DropDownList1.SelectedValue);

            //get the start int for the filter
            int start = end - 5;

            //if the filter is resetted, make sure the query returns all ages
            if (end == 0)
            {
                start = 0;
                end = 99;
            }

            //replace the parameters in the query
            source.SelectParameters.Add("start", start.ToString());
            source.SelectParameters.Add("end", end.ToString());

            //rebind the grid
            GridView1.DataSource = source;
            GridView1.DataBind();
        }
    }
}
VDWWD
  • 35,079
  • 22
  • 62
  • 79
  • Thank you for this, I am on my way home from work, I will attempt this as soon as I am home. I will Comment here to tell you how I get on. Thanks again! – ACostea Dec 12 '16 at 18:23
  • Hi @VDWWD, I am finally having a go at implementing your code but I am having issues with that first line of code you gave me. At the moment, the page just has a gridview, where I have configured the data source and so there is no code behind as of yet. So where would I put this code to edit my query? Thanks! – ACostea Dec 13 '16 at 11:22
  • Also, are you saying that I need to disable the current datasource I have for my gridview and add it manually using the code you have provided? If so, won't that disable my delete linkbuttons? – ACostea Dec 13 '16 at 13:33
  • I used a `SqlDataSource` in my example because it seemed from one of the comments that you were using that. But yes it would be better to use a single datasource for the Grid. There are of course other possibilities to bind an sort GridView data – VDWWD Dec 13 '16 at 13:43
  • Ok, well I have no code behind in my .cs file yet as I just used the easy DataSource to populate the gridview and the delete function. As for the first line of code, how do I go about implementing this to allow me to try the rest of the code? – ACostea Dec 13 '16 at 13:52
  • Also, date of birth is in Dutch, would I just change it to dob or dateofbirth? – ACostea Dec 13 '16 at 13:52
  • Thanks for the edit :), I have created a test page to try your solution from scratch with no previous datasource implemented. I'm just not sure where to edit the query with the first piece of code you provide? – ACostea Dec 13 '16 at 13:59
  • You have to change 'dob` to the column name of the database that hold the dateofbirth value. And I also put the entire cs code on there. But usually when you add a page to a project in Visual Studio it will add a .cs file for you. – VDWWD Dec 13 '16 at 14:04
  • Ok, I used all of your code and when I run the page I get an error. I have added screenshots above to show the error. – ACostea Dec 13 '16 at 14:10
  • Make sure you set a [correct connectionstring](http://stackoverflow.com/questions/8243008/format-of-the-initialization-string-does-not-conform-to-specification-starting-a). otherwise you will get that error. `source.ConnectionString = ...`; – VDWWD Dec 13 '16 at 14:14
  • oh yes, I missed that. Let me set my connection string and i'll test. Thanks! – ACostea Dec 13 '16 at 14:14
  • Ok, sorry if i'm being completely stupid but I have never used the 'source.ConnectionString = ' way of setting a connection string. Mine looks like this but I still get the error when trying to run: source.ConnectionString = "Data Source = THEBEAST; Initial Catalog = newregDB; Integrated Security = True; Pooling = False"; – ACostea Dec 13 '16 at 14:17
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/130522/discussion-between-vdwwd-and-acostea). – VDWWD Dec 13 '16 at 14:23
  • What part of the code would I need to change so that if I make new age groups, the correct ages are displayed when filtering through them? – ACostea Dec 13 '16 at 15:09