凡是做ddl绑定记得2点:ddlType_SelectedIndexChanged绑定,AutoPostBack 设为true
从数据库绑定ddl
//绑定机构
void BindSac()
{
string sqlString = "select StockPool_ssiSac from dbo.StockPool group by StockPool_ssiSac";
SqlHelper sql = new SqlHelper(SqlHelper.stockConString);
DataTable dt = sql.ExecuteDataTable(sqlString);
ddlSac.DataSource = dt;
ddlSac.DataTextField = "StockPool_ssiSac";
ddlSac.DataValueField = "StockPool_ssiSac";
ddlSac.DataBind();
ddlSac.Items.Insert(0,new ListItem("请选择……","0"));
}
void BindSac()
{
string sqlString = "select StockPool_ssiSac from dbo.StockPool group by StockPool_ssiSac";
SqlHelper sql = new SqlHelper(SqlHelper.stockConString);
DataTable dt = sql.ExecuteDataTable(sqlString);
ddlSac.DataSource = dt;
ddlSac.DataTextField = "StockPool_ssiSac";
ddlSac.DataValueField = "StockPool_ssiSac";
ddlSac.DataBind();
ddlSac.Items.Insert(0,new ListItem("请选择……","0"));
}
------------------------------------------------------------------------------------------------------
从页面绑定
HTML
改变ddl时dg中的显示也会改变,那么1、AutoPostBack="True" 2、要绑定ddlType_SelectedIndexChanged事件
Code
//类型下拉框切换绑定
private void ddlType_SelectedIndexChanged(object sender, System.EventArgs e)
{
BindDg();
txteditKey.Text = "";//每次将隐藏域里的id清空
}
//类型下拉框切换绑定
private void ddlType_SelectedIndexChanged(object sender, System.EventArgs e)
{
BindDg();
txteditKey.Text = "";//每次将隐藏域里的id清空
}
注意:如果有分页,所有服务器控件是会保留状态的,如果“保险”类别有第3页,而“基金”类别没有的话,页面就会报错,在切换前要将CurrentPageIndex设为0,在ddlType_SelectedIndexChanged事件中将其设为0没有用,因为页面最先在pageLoad中加载,一加载就报错了,所以应在PageLoad中判断旧页数是否大于新页数,是就将页数清零。
Code
这里Dg.PageSize-1,是由于每到10,20,30都多算一页,所以要减一,不然20+10/20就变成3页了,其实只有2页
注:在Dg.DataBind()之前的Dg都是上一次绑定的Dg