通过另一个组合框的值成员过滤组合框

时间:2015-07-15 07:52:02

标签: c# linq filter combobox

我有2个组合框,我用Linq填充它们。

第一个是名为"城市选择"的组合框:[显示成员:城市名称,价值:城市ID(int)]

当用户从第一个组合框中选择一个值时,我想通过CityID过滤我的第二个组合框。

第二个组合框命名为"部门选择"。

这是代码,但它不起作用。我在最后一个代码块上收到错误。

   private void cb_Bolge_MouseHover(object sender, EventArgs e)
    {
        cb_Bolge.DataSource = k.tbl_Bolges;
        cb_Bolge.DisplayMember = "Bolge_Ad";
        cb_Bolge.ValueMember = "Bolge_ID";
    }

    private void cb_Bolge_ValueMemberChanged(object sender, EventArgs e)
    {
        cb_Departman.DataSource = k.tbl_Departmans.Where(p=>p.Bolge_ID == Convert.ToInt32(cb_Bolge.ValueMember));
        cb_Departman.DisplayMember = "Departman_Ad";
        cb_Departman.ValueMember = "Departman_ID";
    }

这是错误代码(抱歉,其中一些默认情况下是土耳其语):

System.FormatException was unhandled
HResult=-2146233033
Message=Giriş dizesi doğru biçimde değildi.
Source=System.Data.Linq
StackTrace:
konum:      System.Data.Linq.SqlClient.QueryConverter.VisitInvocation(InvocationExpression invoke)
   konum: System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node)
   konum: System.Data.Linq.SqlClient.QueryConverter.VisitExpression(Expression exp)
   konum: System.Data.Linq.SqlClient.QueryConverter.VisitBinary(BinaryExpression b)
   konum: System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node)
   konum: System.Data.Linq.SqlClient.QueryConverter.VisitExpression(Expression exp)
   konum: System.Data.Linq.SqlClient.QueryConverter.VisitWhere(Expression sequence, LambdaExpression predicate)
   konum: System.Data.Linq.SqlClient.QueryConverter.VisitSequenceOperatorCall(MethodCallExpression mc)
   konum: System.Data.Linq.SqlClient.QueryConverter.VisitMethodCall(MethodCallExpression mc)
   konum: System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node)
   konum: System.Data.Linq.SqlClient.QueryConverter.ConvertOuter(Expression node)
   konum: System.Data.Linq.SqlClient.SqlProvider.BuildQuery(Expression query, SqlNodeAnnotations annotations)
   konum: System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
   konum: System.Data.Linq.DataQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator()
   konum: System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   konum: System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   konum: System.Data.Linq.Provider.BindingList.Create[T](DataContext context, IEnumerable`1 sequence)
   konum: System.Data.Linq.DataQuery`1.GetNewBindingList()
   konum: System.Data.Linq.DataQuery`1.System.ComponentModel.IListSource.GetList()
   konum: System.Windows.Forms.CurrencyManager.SetDataSource(Object dataSource)
   konum: System.Windows.Forms.CurrencyManager..ctor(Object dataSource)
   konum: System.Windows.Forms.BindingContext.EnsureListManager(Object dataSource, String dataMember)
   konum: System.Windows.Forms.ListControl.SetDataConnection(Object newDataSource, BindingMemberInfo newDisplayMember, Boolean force)
   konum: System.Windows.Forms.ListControl.set_ValueMember(String value)
   konum: TYH_Envanter.Envanter_Ekle.cb_Bolge_ValueMemberChanged(Object sender, EventArgs e) c:\Users\Arda\Documents\Visual Studio 2013\Projects\TYH Envanter\TYH Envanter\Envanter_Ekle.cs içinde: satır 59
   konum: System.Windows.Forms.ListControl.OnValueMemberChanged(EventArgs e)
   konum: System.Windows.Forms.ListControl.set_ValueMember(String value)
   konum: TYH_Envanter.Envanter_Ekle.cb_Bolge_MouseHover(Object sender, EventArgs e) c:\Users\Arda\Documents\Visual Studio 2013\Projects\TYH Envanter\TYH Envanter\Envanter_Ekle.cs içinde: satır 46
   konum: System.Windows.Forms.Control.OnMouseHover(EventArgs e)
   konum: System.Windows.Forms.Control.WmMouseHover(Message& m)
   konum: System.Windows.Forms.Control.WndProc(Message& m)
   konum: System.Windows.Forms.ComboBox.WndProc(Message& m)
   konum: System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   konum: System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   konum: System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   konum: System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   konum: System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   konum: System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   konum: System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   konum: System.Windows.Forms.Application.Run(Form mainForm)
   konum: TYH_Envanter.Program.Main() c:\Users\Arda\Documents\Visual Studio 2013\Projects\TYH Envanter\TYH Envanter\Program.cs içinde: satır 19
   konum: System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   konum: System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   konum: Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   konum: System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   konum: System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   konum: System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   konum: System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   konum: System.Threading.ThreadHelper.ThreadStart()
   InnerException: 

3 个答案:

答案 0 :(得分:0)

convert int linq expression sql querysql {}} {}} {}} {}} {}} {}} {}} {}} }。因此,您需要创建一个变量并在其中保存值,而不是与此变量匹配。

修改

您的function Convert.ToInt32属性为cb_Bolge.ValueMember属性name且永远不会转换为string。所以你需要获得int

SelectedValue

答案 1 :(得分:0)

我相信你需要在你的IEnumerable上调用“.ToList()”,因为组合框需要一个项目列表(其长度是提前知道的,而不是IEnumerable的情况)。

cb_Departman.DataSource = k.tbl_Departmans
    .Where(p=>p.Bolge_ID == Convert.ToInt32(cb_Bolge.ValueMember))
    .ToList();

答案 2 :(得分:0)

如果我理解得很好,你应该使用Binding。它更清洁,一旦配置就为你做了一切。

在你的xaml中:

<combobox name="first" ItemsSource="{Binding Cities}" SelectedItem="{Binding SelectedCity, mode=TwoWay}" />
<combobox name="second" ItemsSource="{Binding Departments}" />

然后,在您的控制器中,使用INotifyPropertyChanged

public class CitySelector : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(String propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }


    private ObservableCollection<City> cities;
    public ObservableCollection<City> Cities
    {
        get { return cities; }
        set
        {
            if (cities != value)
            {
                cities = value;
                NotifyPropertyChanged("Cities");
            }
        }
    }

    private ObservableCollection<Department> departments;
    public ObservableCollection<Department> Departments
    {
        get { return departments; }
        set
        {
            if (departments != value)
            {
                departments = value;
                NotifyPropertyChanged("Departments");
            }
        }
    }

    private List<Department> MyDepartments;

    private City selectedCity;
    public City SelectedCity
    {
        get { return selectedCity; }
        set
        {
            if (selectedCity != value)
            {
                selectedCity = value;
                if (selectedCity == null)
                    Departments = null;
                else
                    Departments = MyDepartments.Where(x => x.CityId == selectedCity.Id).ToList();
                NotifyPropertyChanged("SelectedCity");
            }
        }
    }

    public CitySelector()
    {
        MyDepartments = new List<Department>() { new Department() { name = "Dep1", CityId = 1}, new Department() {name = "Dep2", CityId = 2}, new Department() {name = "Dep3", CityId = 3 } };
        Cities = new ObservableCollection<City>() { new City() { Id = 1, name = "City 1" }, new City() { Id = 2, name = "City 2" }, new City() { Id = 3, name = "City 3" } };

        this.DataContext = this;
    }
}

如果我错了,请随时纠正我。如果我没有解决你的问题,请给我更多信息。