datagrid的页眉中加入下拉框
如何在datagrid的页眉中中加入下拉框,下拉框绑定到数据源;下拉框改变,datagrid重新绑定?
------解决方案--------------------private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
this.DataGrid1.DataSource = GetData( "SELECT * FROM Employees ORDER BY EmployeeID DESC ");
this.DataGrid1.DataBind();
}
}
private SqlConnection cn = null;
private SqlConnection Open()
{
cn = new SqlConnection( "server=.;uid=sa;pwd=sa;database=northwind; ");
cn.Open();
return cn;
}
private void Close()
{
if(cn != null) cn.Close();
}
private DataSet GetData(string sql)
{
SqlDataAdapter da = new SqlDataAdapter(sql , Open());
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
private void DataGrid1_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if(e.Item.ItemType == ListItemType.Header)
{
TableCell tc = e.Item.Cells[2];
DropDownList ddl = new DropDownList();
ddl.AutoPostBack = true;
ddl.DataSource = GetData( "SELECT DISTINCT CITY FROM Employees ORDER BY CITY DESC ");
ddl.DataTextField = "CITY ";
ddl.DataValueField = "CITY ";
ddl.DataBind();
ddl.Items.Insert(0, new ListItem( " ", " "));
ddl.SelectedIndexChanged +=new EventHandler(ddl_SelectedIndexChanged);
tc.Controls.Add(ddl);
}
}
private void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
this.DataGrid1.DataSource = GetData( "SELECT * FROM Employees WHERE CITY= ' " + ddl.SelectedValue + " ' ");
this.DataGrid1.DataBind();
}
------解决方案--------------------前台
<asp:DataGrid id= "DataGrid1 " style= "Z-INDEX: 101; LEFT: 80px; POSITION: absolute; TOP: 104px "
runat= "server " Width= "704px " Height= "352px " AutoGenerateColumns= "False " BorderColor= "#CC9966 "
BorderStyle= "None " BorderWidth= "1px " BackColor= "White " CellPadding= "4 ">
<FooterStyle ForeColor= "#330099 " BackColor= "#FFFFCC "> </FooterStyle>
<SelectedItemStyle Font-Bold= "True " ForeColor= "#663399 " BackColor= "#FFCC66 "> </SelectedItemStyle>
<ItemStyle ForeColor= "#330099 " BackColor= "White "> </ItemStyle>
<HeaderStyle Font-Bold= "True " ForeColor= "#FFFFCC " BackColor= "#990000 "> </HeaderStyle>
<Columns>
<asp:BoundColumn DataField= "FirstName " HeaderText= "FirstName "> </asp:BoundColumn>
<asp:BoundColumn DataField= "LastName " HeaderText= "LastName "> </asp:BoundColumn>
<asp:BoundColumn DataField= "City " HeaderText= "City "> </asp:BoundColumn>
</Columns>
<PagerStyle HorizontalAlign= "Center " ForeColor= "#330099 " BackColor= "#FFFFCC "> </PagerStyle>
</asp:DataGrid>