我想使用两个CheckBoxList过滤数据,结果必须显示在GridView中。我的数据存储在SQL Server数据库中。 我已经完成了一些代码,但它没有工作,当我检查一些盒子时没有发生任何事情。 这是我的代码
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindList();
}
}
protected void gvDemo_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvDemo.PageIndex = e.NewPageIndex;
BindList();
}
private void BindList()
{
string conString = ConfigurationManager.ConnectionStrings["YMMDMSConnectionString"].ConnectionString;
string query = "SELECT ID,Client,Projet,Date,Shift,CodDefaut FROM cascad";
string condition = string.Empty;
foreach (ListItem item in shift.Items)
{
condition += item.Selected ? string.Format("'{0}',", item.Value) : "";
}
if (!string.IsNullOrEmpty(condition))
{
condition = string.Format(" where Shift in ({0})", condition.Substring(0, condition.Length - 1));
}
string condition2 = string.Empty;
foreach (ListItem item in client.Items)
{
condition2 += item.Selected ? string.Format("'{0}',", item.Value) : "";
}
if (!string.IsNullOrEmpty(condition2))
{
condition2 = string.Format(" AND Client = {0}", condition2.Substring(0, condition2.Length - 1));
}
SqlCommand cmd = new SqlCommand(query + condition + condition2);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
gvDemo.DataSource = ds;
gvDemo.DataBind();
}
}
}
}
protected void shift_SelectedIndexChanged(object sender, EventArgs e)
{
BindList();
}
protected void client_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (ListItem item in shift.Items)
{
if (item.Selected == true)
{
BindList();
}
}
}
}
我错过了什么?
答案 0 :(得分:0)
你don't really need to dispose a DataSet
or DataTable
(即使它实现了IDisposable
,它也仅适用于设计师的东西)。所以using
是多余的。如果您将已处置的DataSet
用作DataSource
,则可能会导致此问题。
所以只是:
DataSet ds = new DataSet())
sda.Fill(ds);
gvDemo.DataSource = ds;
gvDemo.DataBind();
除此之外,还不清楚创建的sql查询是否正确。您是否确认它在Sql-Server Management-Studio中有效?
顺便问一下,为什么要在循环中调用BindList
?你只需要调用一次(如果需要)。所以这可能更合适:
bool needToDatabind = false;
foreach (ListItem item in shift.Items)
{
if (item.Selected == true)
{
needToDatabind = true;
break;
}
}
if(needToDatabind) BindList();
或更简洁:
var selectedItems = shift.Items.Cast<ListItem>().Where(i => i.Selected);
if(selectedItems.Any()) BindList();
答案 1 :(得分:0)
确保您已将AutoPostBack="true"
发送到复选框。
添加断点只需单击以添加断点,如图像中所示,然后按F5进行调试。
希望这有帮助吗?