2011-02-23 2 views
0

다중 선택 콤보 박스를 채우는 C# 예제가 있습니다. 이것은 온라인에서 발견 된 예제에서였습니다. 그것은 관찰 할 수있는 콜렉션에서 오는 정적 값과 잘 동작합니다.C# ObservableCollection 예제를 VB.NET 데이터 세트 또는 이와 동등한 것으로 변환하십시오.

SQL Server 백엔드에서 구동되는 데이터베이스로 변경하려고했지만 문제가있었습니다. 내가 콤보 박스를 채우기 위해 그것을 얻었지만, 선택은 다소 엉성한 행동이다. 다른 사람이 도울 수 있다면 샘플 코드가 있습니다. "Select CategoryName from Categories"와 같이 Northwind 테이블의 간단한 쿼리만으로도 충분합니다.

질문 : 아래 예제에서 사용 된 정적 문자열 목록이 아닌 데이터베이스에서 쿼리를 사용하도록 ObservableCollection을 변환하는 방법은 무엇입니까? 동일한 속성을 구현하는 동안 기능이 변경되었습니다.

class DataSource : INotifyPropertyChanged 
{ 

    #region INotifyPropertyChanged Members 

    public event PropertyChangedEventHandler PropertyChanged; 
    private void OnPropertyChanged(string propertyName) 
    { 
     if (PropertyChanged != null) 
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
    } 

    #endregion 

    private ObservableCollection<string> _animals = new ObservableCollection<string> { "Cat", "Dog", "Bear", "Lion", "Mouse", "Horse", "Rat", "Elephant", "Kangaroo", "Lizard", "Snake", "Frog", "Fish", "Butterfly", "Human", "Cow", "Bumble Bee" }; 

    public ObservableCollection<string> Animals 
    { 
     get { return _animals; } 
    } 

    private string _selectedAnimal = "Cat"; 
    public string SelectedAnimal 
    { 
     get { return _selectedAnimal; } 
     set 
     { 
      _selectedAnimal = value; 
      OnPropertyChanged("SelectedAnimal"); 
     } 
    } 

    private ObservableCollection<string> _selectedAnimals; 
    public ObservableCollection<string> SelectedAnimals 
    { 
     get 
     { 
      if (_selectedAnimals == null) 
      { 
       _selectedAnimals = new ObservableCollection<string> { "Dog", "Lion", "Lizard" }; 
       SelectedAnimalsText = WriteSelectedAnimalsString(_selectedAnimals); 
       _selectedAnimals.CollectionChanged += 
        (s, e) => 
        { 
         SelectedAnimalsText = WriteSelectedAnimalsString(_selectedAnimals); 
         OnPropertyChanged("SelectedAnimals"); 
        }; 
      } 
      return _selectedAnimals; 
     } 
     set 
     { 
      _selectedAnimals = value; 
     } 
    } 

    public string SelectedAnimalsText 
    { 
     get { return _selectedAnimalsText; } 
     set 
     { 
      _selectedAnimalsText = value; 
      OnPropertyChanged("SelectedAnimalsText"); 
     } 
    } string _selectedAnimalsText; 


    private static string WriteSelectedAnimalsString(IList<string> list) 
    { 
     if (list.Count == 0) 
      return String.Empty; 

     StringBuilder builder = new StringBuilder(list[0]); 

     for (int i = 1; i < list.Count; i++) 
     { 
      builder.Append(", "); 
      builder.Append(list[i]); 
     } 

     return builder.ToString(); 
    } 
} 
+0

무엇이 질문입니까? – Gabe

+0

@ 가베 : 업데이트했습니다. 정적 문자열 목록이 아닌 SQL 쿼리를 사용하고 싶습니다. 기본적으로 ObservableCollection은 DB 쿼리로부터 채워질 수 있습니까? 그렇지 않다면 위의 예제를 다른 방식으로 SQL 쿼리에서 작동시키는 방법. – Matt

+0

INotifyCollectionChanged를 구현하는 DataSet 주위의 래퍼를 찾고있는 것처럼 들리므로 ObservableCollection을 대체하기 위해 드롭 인이 가능합니다. DataSet에는 실제로 많은 이벤트 모델이 없으므로 DataSet에서 직접 수행하기가 어려울 수 있지만 RowChanged 등의 이벤트가 있기 때문에 DataSet 내 DataTable로 직접 이동하면 작동 할 수 있습니다. –

답변

0

나는

당신이 데이터 엔티티에 LINQ를 사용하여 생각 해 봤나 ... 나는 상황을 제대로 이해한다면 모르겠지만,?

프로젝트에 ADO.NET 데이터 엔터티 모델을 추가하고 마법사를 사용하여 데이터 원본에 연결하십시오.

는 그런 다음 엔티티 객체에서 원하는 열을 선택하는 LINQ 문을 작성하고 ItemSource으로이 설정

예 :

myDataEntity Context = new myDataEntity(); 

List<Animals> myAnimals = new List<Animals>(); 
myAnimals = Context.Animals.ToList; 

var myItemSource = 
     from a in myAnimals 
     select new { SelectedAnimal = a.animal, SelectedAnimalText = a.animaltext }; 

LINQ 선택 문이 같은 두 개의 필드를 포함하는 익명 형식을 만듭니다 컬럼 ItemSource 예로 설정 한 경우 : SelectedAnimal 및 SelectedAnimalText

이제 방금 설정 한 콤보 상자의 ItemSource 속성

ComboBox.ItemsSource == myItemSource; 

그리고 끝났습니다!

관련 문제