Click here to Skip to main content
15,891,431 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a drop down list for Month. I need to display the data in grid view by selecting the Month. What coding should I write. I'm clueless because I'm new in ASP.Net. Can you help me.
For example, I've selected Month=January. Then the gridview must display the date=12/01/2014

My updated code :

VB
'---LOAD MONTH FROM DROP DOWN---
        
        Dim monthName As String = Me.cmbMonth.SelectedValue
        '---LOAD TAHUN---
        Dim year As Integer = DateTime.Now.Year
        Dim monthNo As Integer =
            Convert.ToDateTime("01-" & monthName & "-" & year).Month
        '---GET FIRST AND LAST DATE---
        Dim FirstDate As New DateTime(year, Convert.ToInt32(Me.cmbMonth.SelectedValue.ToString), 1)
        Dim LastDate As DateTime =
            FirstDate.AddMonths(1).AddDays(-1)

        sql = "SELECT Row_Number() OVER(ORDER BY b.Date) AS ROWNUMBER, a.Name, b.MatricNo, b.Date, b.KaunselingID, b.Status " _
            & "FROM DbStudent.dbo.SMP01_Personal AS a " _
            & "INNER JOIN dbo.Kaunseling AS b ON a.MatricNo = b.MatricNo " _
            & "WHERE Status = '2' And Date >= '"& FirstDate &"' AND Date <= '"& LastDate &"'"

        '---RUN THE QUERY AND BIND THE RESULTING DATASET TO THE GRIDVIEW CONTROL---
        Dim ds As DataSet = GetData(sql)
        If (ds.Tables.Count > 0) Then
            gvList.DataSource = ds
            gvList.DataBind()
        End If


ASP.NET
<td style="width: 58px">Month</td>
                    <asp:DropDownList ID="cmbMonth" runat="server" AutoPostBack="true" Width="100">                              
                        <asp:ListItem Value="1">January</asp:ListItem>
                        <asp:ListItem Value="2">February</asp:ListItem>
                        <asp:ListItem Value="3">March</asp:ListItem>
                        <asp:ListItem Value="4">April</asp:ListItem>
                        <asp:ListItem Value="5">May</asp:ListItem>
                        <asp:ListItem Value="6">June</asp:ListItem>
                        <asp:ListItem Value="7">July</asp:ListItem>
                        <asp:ListItem Value="8">August</asp:ListItem>
                        <asp:ListItem Value="9">September</asp:ListItem>
                        <asp:ListItem Value="10">October</asp:ListItem>
                        <asp:ListItem Value="11">November</asp:ListItem>
                        <asp:ListItem Value="12">December</asp:ListItem>
                    </asp:DropDownList>
                </td>

<%--Table Grid View--%>
        <table class="TableContent" style="width:100%">
            <tr>
                <td valign="top">
                   <asp:gridView id="gvSenaraiP"  CssClass="gridViewTable" autogeneratecolumns="False" allowpaging="True"  Width="100%"  EmptyDataText="No Record"
                       OnRowCommand="gvSenaraiP_RowCommand" runat="server" PageSize="20">
                        <FooterStyle CssClass="gridViewFooter" />
                        <HeaderStyle CssClass="gridViewHeader" />
                        <AlternatingRowStyle CssClass="gridViewAlternating" />

                        <Columns> 
                            <asp:BoundField DataField="ROWNUMBER" HeaderText="No." SortExpression="No." HeaderStyle-Width="2%" ></asp:BoundField>
                            <asp:BoundField DataField="Name" HeaderText="Student Name" SortExpression="Student Name" HeaderStyle-Width="20%"></asp:BoundField>
                            <asp:BoundField DataField="MatricNo" HeaderText="Matric No." SortExpression="Matric No." HeaderStyle-Width="15%"></asp:BoundField>
                            <asp:BoundField DataField="Date" HeaderText="Date" DataFormatString="{0:dd/MM/yyyy}" SortExpression="Date" HeaderStyle-Width="15%"></asp:BoundField>
                        
                        <asp:BoundField DataField="KaunselingID" HeaderText="Hidden">
                                <ItemStyle CssClass="hidden" VerticalAlign="Top" />
                                <HeaderStyle CssClass="hidden" />
                                <FooterStyle CssClass="hidden" />
                            </asp:BoundField> 
                        </Columns>

                        <FooterStyle CssClass="gridViewFooter" />
                        <HeaderStyle ForeColor="White" CssClass="gridViewHeader" />
                        <PagerSettings FirstPageText="<<" LastPageText=">>" Mode="NextPreviousFirstLast" NextPageText=">" PreviousPageText="<" />
                    </asp:gridView>
Posted
Updated 30-Sep-14 15:15pm
v21
Comments
ChauhanAjay 10-Sep-14 22:05pm    
What will be the value of the variable monthName in the query. For example will it Jan or January.
U_Hanisa 10-Sep-14 22:09pm    
January
ChauhanAjay 10-Sep-14 22:18pm    
In the code above your monthName variable is assigned to empty.
I hope it should be assigned to the combobox value.
Change the following line
Dim monthName As String = ""
to
Dim monthName As String = Me.cmbMonth.SelectedValue

and query to
sql = "SELECT a.Name, b.MatricNo, b.Date, b.KaunselingID " _
& "FROM DbStudent.dbo.Personal AS a " _
& "INNER JOIN dbo.Kaunseling AS b " _
& "ON a.MatricNo = b.MatricNo " _
& "WHERE DATENAME(MONTH, DATE) = '" & monthName & "'" _
& "AND Date BETWEEN '"& FirstDate &"' AND '"& LastDate &"'"

Try these things and let me know the result



U_Hanisa 10-Sep-14 22:31pm    
It still the same. Do you mean "WHERE DATENAME(MONTH, DATE) = '" & monthName & "'", I must type 'DATENAME(MONTH, DATE)' too? Is it correct?
ChauhanAjay 10-Sep-14 22:37pm    
Yes you must type that.
After updating the code debug it and copy the value of the variable sql and run it in management studio and see whether it is giving the result or not.

Some simple browsing gives this result at MSDN:

GridView Examples for ASP.NET 2.0[^]

One option is to use the RowFilter property of the DataView.
You don't give much information about your implementation, so I have to guess here.

C#
// This code is just for my debugging
// You have probably already a filled data table.
DataTable dt = new DataTable();
dt.Columns.Add("date", typeof(DateTime));
dt.Rows.Add(new DateTime(2014, 09, 01));
dt.Rows.Add(new DateTime(2014, 10, 01));
dt.Rows.Add(new DateTime(2014, 10, 11));
dt.Rows.Add(new DateTime(2014, 11, 01));
dt.Rows.Add(new DateTime(2014, 11, 04));
dt.Rows.Add(new DateTime(2014, 11, 30));
dt.Rows.Add(new DateTime(2014, 12, 01));

DateTime date = DateTime.Now;
DataView dv = dt.DefaultView;

int month = 10;  // This is the selected Month from the DropDownList

int endDay = 0;
switch (month)
{
    case 2: endDay = 28; break;     // February, Except in leap years. Not solved in this example
    case 4: endDay = 30; break;     // April
    case 6: endDay = 30; break;     // June
    case 9: endDay = 30; break;     // September
    case 11: endDay = 30; break;    // November
    default: endDay = 31; break;    // The rest of the months
}

DateTime startDate = new DateTime(DateTime.Now.Year, month, 1);
DateTime endDate = new DateTime(DateTime.Now.Year, month, endDay);

// Assuming you have a column named 'date' in your data table, 
// otherwise change to the appropriate column name
dv.RowFilter = String.Format("date >= '{0}' AND date <= '{1}'", startDate, endDate);

// Then assign dv to your GridView


Another, and maybe better option, would be to send a new request to the database when a new month is selected.
Then you use the WHERE clause in the SELECT statement.
I am not so good at SQL, so I leave that part to you.

One place to start with SQL is here: w3schools: SQL Tutorial[^]
Especially The SQL WHERE Clause[^]

Using the creation of startDate and endDate from the code above you can try the code below.
C#
string sqlCommand = String.Format(@"SELECT [column1], [column2] FROM [table] WHERE Date BETWEEN '{0}' AND '{1}'", startDate.ToString("MM/dd/yyyy"), endDate.ToString("MM/dd/yyyy"));
// Note that the date format string must match the format in your database.

As this code is in c#, you might want to look at the links below in order to convert to VB.
The difference should be minimal.
String.Format Method[^]
and
http://msdn.microsoft.com/en-us/library/system.string.format(v=vs.110).aspx[^]

Someone else can probably show you a better SQL query.
 
Share this answer
 
v5
Comments
U_Hanisa 9-Sep-14 22:35pm    
I did it before. But my selected value is Month while my data is the whole date. What should I write to display the date and the rest of data with only choosing a Month
George Jonsson 9-Sep-14 23:50pm    
I updated my answer with a code example.
U_Hanisa 10-Sep-14 0:21am    
This is my last coding
Sub LoadList()

'---LOAD LIST---
dbconn = New OleDb.OleDbConnection(strCon)
dbconn.Open()

sql = "SELECT [column1], [column2] FROM [table] WHERE Date = '"& Me.cmbMonth.SelectedValue"

dbcomm = New OleDbCommand(sql, dbconn)
Dim da As OleDb.OleDbDataAdapter
da = New OleDbDataAdapter(dbcomm)
Dim ds As DataSet
ds = New DataSet
da.Fill(ds, "[table]")
gvList.DataSource = ds.Tables("[table]")
gvList.DataBind()

dbconn.Close()
dbconn = Nothing
End Sub

Do I need to change anything in source too?
George Jonsson 10-Sep-14 0:41am    
Does your code work?
You should have tagged your question with VB, though.
Also, you should use 'Improve Question' and add the code above. It will help others to provide better answers to your question.
U_Hanisa 10-Sep-14 0:52am    
No, it doesn't work. That's why I ask the question here.
VB
'''/u need to get year also coz ur database may contain
'''/months of many years ie.2014,2013,2012,2011,....
'''/fetch month from drop down
Dim monthName As String = "January"
'''/fetch year
Dim year As Integer = 2014
Dim monthNo As Integer = Convert.ToDateTime((Convert.ToString("01-") & monthName) + "-" + year).Month
'''////get first and last date
Dim FirstDate As New DateTime(year, monthNo, 1)
Dim lastDate As DateTime = FirstDate.AddMonths(1).AddDays(-1)
'''////use select query with BETWEEN operator
'''////samples found in below link
'''/http://74.125.224.72/#q=sql+between+two+dates


'''////good luck ;-)

'=======================================================
'Service provided by Telerik (www.telerik.com)
'Conversion powered by NRefactory.
'Twitter: @telerik
'Facebook: facebook.com/telerik
'=======================================================



---replace ur sql value like below

VB
sql = "SELECT a.Name, b.MatricNo, b.Date, b.KaunselingID FROM DbStudent.dbo.Personal AS a INNER JOIN dbo.Kaunseling AS b ON a.MatricNo = b.MatricNo WHERE Date >= (datevalue('" & FirstDate & "') + timevalue('" & FirstDate & "')) and Date <= (datevalue('" & lastDate & "') + timevalue('" & lastDate & "')) "


---u should try to use parameterized query for a secured way
-----http://stackoverflow.com/questions/22976492/how-to-select-data-between-two-date-ranges-using-datepicker-c-sharp[^]
 
Share this answer
 
v2
Comments
U_Hanisa 10-Sep-14 20:40pm    
Thank you..I'd update my coding. By the way, how to load the details that link with the month that I select. Can you please check for me, because it still cannot run. The gridview didn't display anything.
george4986 11-Sep-14 0:10am    
plz check updated solution
U_Hanisa 11-Sep-14 0:22am    
What do you mean by 'datevalue' and 'timevalue'? Is it '2014-08-20 00:00:00'
george4986 11-Sep-14 1:44am    
to check date with time
U_Hanisa 11-Sep-14 2:53am    
It still don't display anything. Huwarghh..I feel want to cry, I want to give up. I hate prgramming :'(
VB
Sub LoadList()   '---LOAD DATA TO GRIDVIEW---

        '---LOAD LIST---
        dbconn = New OleDb.OleDbConnection(strCon)
        dbconn.Open()

        '---LOAD MONTH FROM DROP DOWN---
        Dim monthName As String = Me.cmbBulan.SelectedValue
        '---LOAD YEAR---
        Dim year As Integer = 2014
        Dim monthNo As Integer =
            Convert.ToDateTime("01-" & monthName & "-" & year).Month
        '---GET FIRST AND LAST DATE---
        Dim FirstDate As New DateTime(year, Convert.ToInt32(Me.cmbBulan.SelectedValue.ToString), 1)
        Dim LastDate As DateTime =
            FirstDate.AddMonths(1).AddDays(-1)

        sql = "SELECT Row_Number() OVER(ORDER BY b.Date) AS ROWNUMBER, a.Name, b.MatricNo, b.Date, b.KaunselingID " _
            & "FROM DbStudent.dbo.Personal AS a " _
            & "INNER JOIN dbo.Kaunseling AS b ON a.MatricNo = b.MatricNo " _
            & "WHERE convert(datetime, Date, 103) >= '" & FirstDate & "' AND convert(datetime, Date, 103) <= '" & LastDate & "'"

        '---RUN THE QUERY AND BIND THE RESULTING DATASET TO THE GRIDVIEW CONTROL---
        Dim ds As DataSet = GetData(sql)
        If (ds.Tables.Count > 0) Then
            gvList.DataSource = ds
            gvList.DataBind()
        End If

        dbconn.Close()
        dbconn = Nothing
    End Sub
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900