前台代码:
<div> <asp:CheckBoxList ID="CheckBoxList1" runat="server" AutoPostBack="True"> <asp:ListItem Text="Sunny" Value="Sunny"></asp:ListItem> <asp:ListItem Text="Mike" Value="Mike"></asp:ListItem> <asp:ListItem Text="Jakes" Value="Ken"></asp:ListItem> <asp:ListItem Text="Ken" Value="Ken"></asp:ListItem> </asp:CheckBoxList> <hr /> <br /> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"> <Columns> <asp:TemplateField HeaderText="ID"> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text=‘<%#Eval("ID") %>‘></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Name"> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text=‘<%#Eval("Name") %>‘></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="City"> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text=‘<%#Eval("City") %>‘></asp:Label> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </div>
后台代码:
protected void Page_Load(object sender, EventArgs e) { string strwhere = ""; foreach (ListItem item in CheckBoxList1.Items) { if (item.Selected) { strwhere += "‘" + item.Value.ToString() + "‘,"; } } BindGridView(strwhere); } public void BindGridView(string Names) { DataTable dt=new DataTable(); using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DemosDatabaseConnectionString"].ConnectionString)) { conn.Open(); if (Names.Length <= 0) { string sql = "select * from Customers"; SqlDataAdapter sda = new SqlDataAdapter(sql,conn); sda.Fill(dt); GridView1.DataSource = dt; GridView1.DataBind(); } else { string sql = "select * from Customers where Name in (" + Names.Substring(0, Names.Length - 1) + ")"; SqlDataAdapter sda = new SqlDataAdapter(sql, conn); sda.Fill(dt); GridView1.DataSource = dt; GridView1.DataBind(); } } }
http://forums.asp.net/t/2042553.aspx
时间: 2024-11-13 08:03:44