根据所选日期显示SQL数据

时间:2015-05-04 08:57:18

标签: c# sql sql-server gridview

我是ASP.NET的新手 我有一个显示SQL表数据的GridView。 我想根据从Calendar或Textbox中选择的日期在GridView中显示数据。 这是代码:

<p><asp:Label ID="Date" runat="server">Select Date:</asp:Label>

  <asp:Calendar ID="Calendar2" runat="server"  SelectionMode="DayWeekMonth" onselectionchanged="Calendar1_SelectionChanged">
        </asp:Calendar>

    <p>Todays Date is:  <asp:Label ID="lblday" runat="server"></asp:Label></p>
    <p>Selected Date is:<asp:Label ID="lblbday" runat="server"></asp:Label></p>

<asp:Button ID="addDates" runat="server" Text="Display" class="button1" 
        style="margin-left: 137px" Width="150px" />
    </p>
<!--<p><asp:Calendar ID="drdates" runat="server" class="textbox1"></asp:Calendar>-->


    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        DataSourceID="SqlDataSource1" Height="178px" Width="402px">
        <Columns>
            <asp:BoundField DataField="scode" HeaderText="scode" SortExpression="scode" />
            <asp:BoundField DataField="drdates" HeaderText="drdates" 
                SortExpression="drdates" />
            <asp:BoundField DataField="Column1" HeaderText="Column1" ReadOnly="True" 
                SortExpression="Column1" />
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:AbcConnectionString %>" 
        SelectCommand="select scode, drdates, count(*) from drreceive_20141229 group by drdates, scode">
    </asp:SqlDataSource>

这是C#代码:

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

namespace ISYSProject
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void Calendar1_SelectionChanged(object sender, EventArgs e)
        {
            lblday.Text = Calendar2.TodaysDate.ToShortDateString();
            lblbday.Text = Calendar2.SelectedDate.ToShortDateString();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

执行以下操作:

  1. 在SQLDataSource1数据源上,进入[属性]&gt;&gt; [选择命令]并单击&#34;添加参数&#34;并填写详细信息(参数来源=&#34;控制&#34;其余部分不言自明)。
  2. 更新您的SQL查询以包含参数&#34; ..... drreceive_20141229其中drdate = @ WhateverYouCalledParameter&#34;
  3. 更新您的&#34; Calendar1_SelectionChanged&#34;并添加&#34; SQLDataSource1.databind();&#34;
  4. 应该是它。