2009-07-07 4 views
11

나는이 같은 DataGridViewComboBoxColumn을 설정하고 있습니다 :각 셀에 다른 데이터 소스로 DataGridView ComboBoxColumn을 설정하는 방법은 무엇입니까?

var newColumn = new DataGridViewComboBoxColumn() { 
    Name = "abc" 
}; 
newColumn.DataSource = new string[] { "a", "b", "c" }; 
dgv.Columns.Add(newColumn); 

이 작동 : 각 행은 A, B, C로 채워 해당 열의 드롭 다운 상자를 가지고 있습니다.

그러나 이제 특정 행에 대한 목록을 자르고 싶습니다. 나는이 같은 행마다의 목록을 설정하기 위해 노력하고있어 :

foreach (DataGridViewRow row in dgv.Rows) { 
    var cell = (DataGridViewComboBoxCell)(row.Cells["abc"]);   
    cell.DataSource = new string[] { "a", "c" };       
} 

그러나,이 코드는 효과가 없습니다 - 모든 행은 여전히 ​​"A", "B", "C"를 보여줍니다.

나는 아무 소용 new List<string>new BindingList<string>, 모두 new string[]를 교체 시도했다.

또한 newColumn.DataSource을 설정하는 코드를 제거하려고했지만 목록이 비어 있습니다.

이 작업을 올바르게 수행하려면 어떻게해야합니까? 나를 위해

답변

20

다음 작품 :

DataGridViewComboBoxColumn newColumn = new DataGridViewComboBoxColumn(); 
newColumn.Name = "abc"; 
newColumn.DataSource = new string[] { "a", "b", "c" }; 
dataGridView1.Columns.Add(newColumn); 

foreach (DataGridViewRow row in dataGridView1.Rows) 
{ 
    DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)(row.Cells["abc"]); 
    cell.DataSource = new string[] { "a", "c" }; 
} 

또한 시도해 볼 수도 있습니다 (이 또한 나를 위해 작동) :

for (int row = 0; row < dataGridView1.Rows.Count; row++) 
{ 
    DataGridViewComboBoxCell cell = 
     (DataGridViewComboBoxCell)(dataGridView1.Rows[row].Cells["abc"]); 
    cell.DataSource = new string[] { "f", "g" }; 
} 
+0

흠, 그건 저에게도 도움이됩니다 - 깨끗한 테스트 프로젝트에서. 그것은 내가 다르게하고있는 것이어야합니다. – Blorgbeard

+3

문제는 내 DataGridView에 AutoSizeColumnMode가 AllCells로 설정되어 있다는 것과 관련이 있습니다. 데이터 소스가 설정되기 전에 셀의 값을 확인했다고 생각합니다. – Blorgbeard

+1

내 문제를 도와 줘! – XXXXX

0

또 다른 옵션은 행 수준에서 데이터 바인딩을 시도하는 것입니다. OnRowDataBound 이벤트를 사용해보십시오. 그런 다음 해당 행의 내용을 기반으로 콤보 상자에있는 내용을 프로그래밍 방식으로 설정할 수 있습니다.

물론, 이것은 당신이 그리드 데이터 바인딩을하고 있다고 가정합니다.

+2

나는 데이터 바인딩을하고 있는데, 이것은 웹이 아니라 winforms이다. winforms datagridview에이 이벤트가없는 것 같습니다. – Blorgbeard

관련 문제