2017-04-06 133 views
0

我一直在努力解决这个问题几天了,我还没有找到任何答案;我创建了一个ToolStripMenu阵列从一个存储过程动态填充:使用列表内容过滤datagridview C#

ToolStripMenuItem[] itemsDepto = null; 
itemsDepto = new ToolStripMenuItem[data.Tables[0].Rows.Count]; 
for (int i = 0; i <= data.Tables[0].Rows.Count - 1; i++) 
{ 
    itemsDepto[i] = new ToolStripMenuItem(); 
    itemsDepto[i].Tag = data.Tables[0].Rows[i].ItemArray[0]; 
    itemsDepto[i].Text = data.Tables[0].Rows[i].ItemArray[1].ToString(); 
    itemsDepto[i].CheckOnClick = true; 
    itemsDepto[i].Checked = true; 
    itemsDepto[i].Click += DeptoFilter_Click; 
    deptoList.Add(data.Tables[0].Rows[i].ItemArray[1].ToString()); 
} 
tsmiDepartamento.DropDownItems.AddRange(itemsDepto); 

而且我想要实现的是使用该ToolStripMenu作为用户的过滤器控制,默认情况下被选中状态,以便当用户取消选中在菜单中,它应该过滤未被选中内容的行。

Click事件中我添加和删除列表取决于菜单按钮的状态值,你可以在下面的例子中看到:

private void DeptoFilter_Click(object sender, EventArgs e) 
{ 
    ToolStripMenuItem temp = new ToolStripMenuItem(); 
    temp = (ToolStripMenuItem)sender; 
    BindingSource bind = new BindingSource(); 
    bind.DataSource = dgvPersonalTotal.DataSource; 
    if (temp.CheckState == CheckState.Checked) 
    { 
     deptoList.Add(sender.ToString()); 
    } 
    else 
    { 
     deptoList.Remove(sender.ToString()); 
    } 
    bind.Filter = "Departamento NOT IN (" + /*LIST*/"" + ")"; 
    dgvPersonalTotal.DataSource = bind; 
    //foreach (string x in deptoList) 
    //{ 
    //} 
} 

但最大的问题我有,我怎样才能使用列表过滤绑定源,如你可以在代码中看到的,我不能只使用列表,甚至尝试在foreach中使用BindingSource.Filter,我不知道如何解决这个问题,所以任何想法都很受赞赏。

+0

deptoList是什么类型的? – Alon

+0

List deptoList = new List (); – cyberac75

回答

0
bind.Filter = "Departamento NOT IN (" + string.Join(",", deptoList.ToArray()) + ")"; 
+0

这对我很好,因为这个想法:bind.Filter =“Departamento IN(”+ string.Join(“,”,deptoList.Select(x =>“'”+ x +“'”))+ “)” – cyberac75

+0

我不能投票,但我会给你正确的答案,但是任何想要使用此代码的人都需要知道这不是正确的答案,它会导致你的代码崩溃异常:抛出的异常:System.Data.dll中的'System.Data.SyntaxErrorException',请使用上面评论中发布的答案 – cyberac75