需求
在一个查询报表列出所有记录,每列的表头上是dropdownlist,列出该列所有数据,用户可以选择多列,形成组合过滤条件,每次用户改变dropdownlist的过滤条件,页面重新刷新。
实现方法:
使用Gridview先是数据,绑定sqldatasource数据源DataSource_PipeLine,Gridview要过滤的列定义为Template列。将dropdownlist加入HeaderTemplate。需要处理SelectedIndexChanged事件,来计算出过滤条件。
代码:
protected void DropDownListCustomers_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList DropDownListCustomers = (DropDownList)sender;
string CustomerFilter = string.Format("CustomerID={0}", DropDownListCustomers.SelectedValue);
DataSource_PipeLine.FilterExpression = GetfilterString();
}
此时,发现一个问题,每次页面刷新后,dropdownlist的当前值都被重新设置为0。例如,DropDownListCustomers 有10个item,当用户选择了位于第3位的Customer 3,页面过滤后显示的数据是Customer 3的纪录,但DropDownListCustomers 的当前选项还是第一位。
这是因为在给DataSource_PipeLine加上过滤条件后,数据重新绑定了,所有的dropdownlist也都被重新绑定了一遍,为了保持表头和内容的一致,还要多做一步处理。在dropdownlist重新绑定后,将当前index重设,为此,需要处理DataBound事件。
protected void DropDownListCustomers_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList DropDownListCustomers = (DropDownList)sender;
string CustomerFilter = string.Format("CustomerID={0}", DropDownListCustomers.SelectedValue);
DataSource_PipeLine.FilterExpression = GetfilterString();
//处理用户选择时,记住当前选择
DropDownListCustomersIndex = DropDownListCustomers .SelectedIndex;
}
protected void DropDownListCustomers_DataBound(object sender, EventArgs e)
{
//重新绑定后,重设index
((DropDownList)sender).SelectedIndex = DropDownListCustomersIndex;
}