2011-10-03 2 views
4

디자인 클래스 : 엔티티에 바인딩 된 콤보 박스에 새 항목을 추가하는 방법은 무엇입니까? C 번호로 생성

// 
    // usepurposeComboBox 
    // 
    this.usepurposeComboBox.DataSource = this.usepurposeBindingSource; 
    this.usepurposeComboBox.DisplayMember = "Name"; 
    this.usepurposeComboBox.FormattingEnabled = true; 
    this.usepurposeComboBox.Location = new System.Drawing.Point(277, 53); 
    this.usepurposeComboBox.Name = "usepurposeComboBox"; 
    this.usepurposeComboBox.Size = new System.Drawing.Size(218, 21); 
    this.usepurposeComboBox.TabIndex = 4; 
    this.usepurposeComboBox.ValueMember = "id"; 
    // 
    // usepurposeBindingSource 
    // 
    this.usepurposeBindingSource.DataSource = typeof(mydatabaseEntities.usepurpose); 

그럼 내가 엔티티에 BindingSource에 (usepurposeBindingSource)를 구속은 : 바인드되어 있기 때문에

usepurposeBindingSource.DataSource = mydatabaseEntities.usepurposes; 

그리고 usepurposeComboBox에 새 행을 추가 할 수 없습니다. 해결 방법이 있습니까?

답변

0

나는 혼자 해결했다. 새로운 언 바운드 콤보 박스를 만든 다음 데이터 테이블에 바인딩합니다. 그것이 최선의 방법인지 확실하지 않지만 그것이 나를 위해 작동합니다. 귀하의 모든 제안에 감사드립니다. :)

private void FillCombobox() 
     { 
      using (mydatabaseEntities mydatabaseEntities = new mydatabaseEntities()) 
      { 
       List<usepurpose> usepurposes = mydatabaseEntities.usepurposes.ToList();    
       DataTable dt = new DataTable(); 
       dt.Columns.Add("id"); 
       dt.Columns.Add("Name"); 
       dt.Rows.Add(-1, "test row"); 
       foreach (usepurpose usepurpose in usepurposes) 
       { 
        dt.Rows.Add(usepurpose.id, usepurpose.Name); 
       } 
       usepurposeComboBox.ValueMember = dt.Columns[0].ColumnName; 
       usepurposeComboBox.DisplayMember = dt.Columns[1].ColumnName; 
       usepurposeComboBox.DataSource = dt; 
      } 
     } 
0

예를 들어 "Choose One"이라고하는 첫 번째 항목을 추가하려는 경우 데이터를 살고 싶은 곳에서 데이터를 가져와야 할 곳을보고 "테이블"에 항목을 추가해야합니다.

this.usepurposeBindingSource은 개체입니다 ... 왜 바인딩하기 전에 추가하지 않으시겠습니까?

그것이 List<T>의 경우이 그런

this.usepurposeBindingSource.Insert(0, new T() { 
    Name = "Choose one", 
    Id = "" 
}); 

Bind()을 ...

이 문자열의로 검증 할 기억 잘 될 것입니다 및 개체가 원하는되지 않습니다


정상 작동 중 :

List<MyObject> usepurposeBindingSource { get; set; } 

private void FillUpData() 
{ 
    // Simulating an External Data 
    if (usepurposeBindingSource == null || usepurposeBindingSource.Count == 0) 
    { 
     this.usepurposeBindingSource = new List<MyObject>(); 
     this.usepurposeBindingSource.Add(new MyObject() { Name = "A", ID = 1 }); 
     this.usepurposeBindingSource.Add(new MyObject() { Name = "B", ID = 2 }); 
     this.usepurposeBindingSource.Add(new MyObject() { Name = "C", ID = 3 }); 
    } 
} 

private void FillUpCombo() 
{ 
    FillUpData(); 

    // what you have from design 
    // comment out the first line 
    //this.usepurposeComboBox.DataSource = this.usepurposeBindingSource; 
    this.usepurposeComboBox.DisplayMember = "Name"; 
    this.usepurposeComboBox.FormattingEnabled = true; 
    this.usepurposeComboBox.Location = new System.Drawing.Point(277, 53); 
    this.usepurposeComboBox.Name = "usepurposeComboBox"; 
    this.usepurposeComboBox.Size = new System.Drawing.Size(218, 21); 
    this.usepurposeComboBox.TabIndex = 4; 
    this.usepurposeComboBox.ValueMember = "id"; 

    // to do in code: 

    this.usepurposeBindingSource.Insert(0, new MyObject() { Name = "Choose One", ID = 0 }); 

    // bind the data source 
    this.usepurposeComboBox.DataSource = this.usepurposeBindingSource; 

} 

트릭은 DataSource 줄을 주석하고 이 모델에서 당신의 객체로 또 하나의 요소를 삽입하는 코드에서 그것을 할 것입니다

//this.usepurposeComboBox.DataSource = this.usepurposeBindingSource;

+1

그것은 할 수 없습니다. System.Windows.Forms.dll에서 'System.ArgumentException'형식의 처리되지 않은 예외가 발생했습니다. 추가 정보 : DataSource 속성을 설정하면 Items 컬렉션을 수정할 수 없습니다. – JatSing

+0

왜 'this.usepurposeBindingSource'에 추가하지 않습니까? – balexandre

0

이 작업을 수행하는 가장 간단한 방법 BindingSource를 일종의 "ViewModel"로 래핑하는 것입니다. 새 클래스는 원래 바인딩 소스에서 제공된 항목과 "추가"항목의 "완전한"목록을 반환합니다.

그런 다음 새 래퍼를 콤보 상자에 바인딩 할 수 있습니다.

나는 이것에 대해 article을 썼다 ... 그것은 나의 가장 훌륭한 작품이 아니며, 아마도 구식이긴하지만, 거기에 당신을 데려다 줄 것이다.

1

가장 짧은 방법은 데이터 테이블에 새 행을 추가 한 후이 같은 당신의 콤보 상자에 바인딩하는 것입니다) (

회사 콤프 = 새로운 회사;

 //pupulate dataTable with data 
     DataTable DT = comps.getCompaniesList(); 

     //create a new row 
     DataRow DR = DT.NewRow(); 
     DR["c_ID"] = 0; 
     DR["name"] = "Add new Company"; 
     DR["country"] = "IR"; 

     //add new row to data table 
     DT.Rows.Add(DR); 

     //Binding DataTable to cxbxCompany 
     cxbxCompany.DataSource = DT; 
     cxbxCompany.DisplayMember = "name"; 
     cxbxCompany.ValueMember = "c_ID"; 
0

체크 아웃 : http://forums.asp.net/t/1695728.aspx/1?

ASP에서 당신은 빈 줄을 삽입하려면이 옵션을 추가 할 수 있습니다

<asp:DropDownList ID="CustomerDropDownList" runat="server" 
    DataSourceID="CustomerEntityDataSource" DataTextField="CustomerId" 
    DataValueField="CustomerId" AppendDataBoundItems="true"> 
    <asp:ListItem Text="Select All Customers" Value="" /> 
    </asp:DropDownList> 

또는 뒤에 코드

는 :

DropDownList1.AppendDataBoundItems = true; 
    DropDownList1.Items.Add(new ListItem("Select All Customers", "-1")); 
+0

AppendDataBoundItems 특성은 Combox가 아닌 DropDownLists에만 사용할 수있는 것 같습니다. – newenglander

관련 문제