小弟用的是vs05,想用dropdownlist来筛选记录,dropdownlist是显示的年份和月份(本来还想做个2级联动的,现在想想还是就直接做一个好了)比如说“06年10月”。gridview用的是sqldatasource,是一个月报表。
现在就有两个问题。1、dropdownlist如何才能显示出“06年10月”这种字段。
2、表中数据是按天更新的。就是想问,怎样才能用上面描述的那种dropdownlist把他们给按月筛选开?
麻烦各位了...

解决方案 »

  1.   

    首先,配置SqlDataSource:<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:testConnectionString1 %>"
        ProviderName="<%$ ConnectionStrings:testConnectionString1.ProviderName %>" SelectCommand="SELECT * FROM [table1] WHERE (datepart(year,[date]) = @year) AND (datepart(month,[date]) = @month) " OnSelecting="SqlDataSource1_Selecting">
        <SelectParameters>
            <asp:Parameter Name="@year" Type="Int32" />
            <asp:Parameter Name="@month" Type="Int32" />
        </SelectParameters>
    </asp:SqlDataSource>
      

  2.   

    然后,代码:protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindDropDown();
        }
     
    }
    protected void BindDropDown()
    {
        DateTime t = DateTime.Now;
        int l = 24;//显示今天以前的24个月
        for (int i = l; i >=0; i--)
        {
            DateTime ttt = t.AddMonths(-i);
            this.DropDownList1.Items.Add(new ListItem(ttt.ToString("yyyy年M月"),ttt.ToShortDateString()));
        }
    }protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
        string tmp = this.DropDownList1.SelectedValue;
        DateTime t = DateTime.Parse(tmp);
        e.Command.Parameters[0].Value = t.Year;
        e.Command.Parameters[1].Value = t.Month;
    }
      

  3.   

    如果楼主还希望DropDownList自动触发这个筛选操作,那么请把DropDownList控件的AutoPostBack属性设置为true,并且添加代码:
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.SqlDataSource1.DataBind();
        }
      

  4.   

    先谢谢005兄的回答...不过还是有几个问题,不加那个OnSelecting="SqlDataSource1_Selecting"还好,一加就出现Must declare the variable '@year'   这个变量不是在下面定义了么,为什么还会出错。
    然后就是关于那dropdownlist的问题了,其实我没说清楚,那dropdownlist应该也是和一个数据源绑定的,就是和gridview用的是同一个表,只是用的字段只有该表里的“date”。象您这样做的话
    【DateTime t = DateTime.Now;
    int l = 24;//显示今天以前的24个月
    for (int i = l; i >=0; i--)···】
    就只能显示出2年内的数据...当然,可以把数字改下。但是,如果这个表只有最近几个月的数据的话,那前面的一些月份感觉就没什么用了,所以就想和表里的date绑定下^^
    不知道我这么想有什么地方错的不。