2008-10-20 4 views
9

NameValue 컬렉션을 GridView에 바인드 할 수 있도록 변환해야하는 컬렉션은 무엇입니까? 직접 할 때 작동하지 않습니다. 영문NameValueCollection을 GridView에 바인딩 하시겠습니까?

<asp:GridView ID="resultGV" runat="server" AutoGenerateColumns="False" Width="100%"> 
    <Columns> 
     <asp:BoundField DataField="Key" HeaderText="Key" /> 
     <asp:BoundField DataField="Value" HeaderText="Value" /> 
    </Columns> 
</asp:GridView> 

모든 팁 환영의 aspx.cs

private void BindList(NameValueCollection nvpList) 
    { 
    resultGV.DataSource = list; 
    resultGV.DataBind(); 
    } 

코드에서

코드입니다. 감사. X.

답변

8

문자열 > 대신 Dictionary < 문자열을 사용할 수 있습니까? NameValueCollection. 사전 T, T >는 IEnumerable을 구현 < 때문에 그렇게으로 LINQ를 사용할 수 있습니다

resultGV.DataSource = from item in nvpDictionary 
         select new { Key = item.Key, Value = item.Value }; 
resultGV.DataBind(); 

[편집] 실제로 직접으로 사전을 사용할 수 있습니다 : 그것은 매핑되지 않는 경우

resultGV.DataSource = nvpDictionary; 
resultGV.DataBind(); 

키/값 원하는 방식으로 항상 LINQ로 돌아갈 수 있습니다. LINQ를 사용하여 필드의 이름을 원하는대로 변경할 수 있습니다.

[편집] 사전 < T, T >을 사용하도록 변경할 수 없으면 메서드에서 NameValueCollection의 복사본을 사전으로 만들어 바인딩하십시오.

private void BindList(NameValueCollection nvpList) 
{ 
    Dictionary<string,string> temp = new Dictionary<string,string>(); 
    foreach (string key in nvpList) 
    { 
     temp.Add(key,nvpList[key]); 
    } 

    resultGV.DataSource = temp; 
    resultGV.DataBind(); 
} 

이렇게 많이하면 사전으로 변환하는 확장 방법을 작성하여 사용할 수 있습니다.

public static class NameValueCollectionExtensions 
{ 
    public static Dictionary<string,string> ToDictionary(this NameValueCollection collection) 
    { 
     Dictionary<string,string> temp = new Dictionary<string,string>(); 
     foreach (string key in collection) 
     { 
      temp.Add(key,collection[key]); 
     } 
     return temp; 
    } 
} 

private void BindList(NameValueCollection nvpList) 
{ 
    resultGV.DataSource = nvpList.ToDictionary(); 
    resultGV.DataBind(); 
} 
+0

Ext 개체로 사전을 변경할 수없고 여전히 Net 2.0을 사용하고 있습니다. 하지만 고마워. 어쨌든. 모든 의견이 도움이됩니다. –

+0

Dictionary는 그렇지 않지만 NameValueCollection에는 중복 키가있을 수 있습니다. 따라서 문제가 생기거나 사전으로 변환 할 때 정보를 잃을 수 있습니다. – magnattic

2

마지막으로 나는 확장 구현에 제안 된 솔루션을 사용했지만 확장 자체는 제안하지 않았습니다.

private void BindList(NvpList nvpList) 
    { 
    IDictionary dict = new Dictionary<string, string>(); 

    foreach (String s in nvpList.AllKeys) 
     dict.Add(s, nvpList[s]); 

    resultGV.DataSource = dict; 
    resultGV.DataBind(); 
    } 

어쩌면 정적이 될 수있는 일부 도우미 클래스를 수행하고 많은 대신 한 곳에서 번역을 수행합니다. 이 확장 프로그램은 매우 편리합니다. :-)

감사합니다. X

6

enumerator은 키만 반환하기 때문에 약간 까다 롭습니다. 당신은 (나는 확신도 또는 GridView) 중첩 Repeater이있는 경우

<asp:GridView id="gv" runat="server" AutoGenerateColumns="false"> 
    <Columns> 
     <asp:TemplateField HeaderText="Key"> 
     <ItemTemplate><%# Container.DataItem %></ItemTemplate> 
     </asp:TemplateField> 
     <asp:TemplateField HeaderText="Value"> 
     <ItemTemplate> 
      <%# ((NameValueCollection)gv.DataSource)[(string)Container.DataItem] %> 
     </ItemTemplate> 
     </asp:TemplateField> 
    </Columns> 
</asp:GridView> 
+0

NameValueCollection과 함께 중첩 된 DataBound Repeater와 같은 컨트롤을 사용하는 경우 필요한 변경 사항에 대한 내 대답을 참조하십시오. –

1

: 그러나, 당신은 Container.DataItem와 키 값을 얻을, 다음 값을 얻기 위해 NameValueCollection은에 찾아 볼 수 있습니다 Mark Brackett's answer을 이와 같이 변경해야합니다. 그렇지 않으면 rpt이라는 이름의 컨트롤을 찾을 수 없다는 런타임 오류가 발생합니다.

<asp:Repeater ID="rpt" runat="server"> 
<ItemTemplate> 
    <li> 
     <%# Container.DataItem %>: 
     <%# ((NameValueCollection)((Repeater)Container.Parent).DataSource)[(string)Container.DataItem] %> 
    </li>  
</ItemTemplate> 
</asp:Repeater> 
1

가 나는 비슷한 문제가의 GridView에 (정말 SortedDictionary) 사전을 결합 포함하고 이름을 변경하고자했다

Dim sDict as New StringDictionary 
sDict.Add("1","data1") 
sDict.Add("2","data2") 
sDict.Add("3","data3") 
... 

CheckBoxList1.DataSource = sDict 
CheckBoxList1.DataValueField = "key" 
CheckBoxList1.DataTextField = "value" 
CheckBoxList1.DataBind() 
0

키 & 값에 접근 &을 데이터 바인딩에 대한 StringDictionary를 사용하도록 최선을 찾을 수있는 열. 나에게 효과가 있었던 것은 읽을만한 것이 조금있다. 이 그것으로 그것을 강요의 Container.DataItem의의 GridView 표시하려고하는 현재 항목을 복용하여 작동

<asp:GridView ID="gv" runat="server" AutoGenerateColumns="False"> 
    <Columns> 
    <asp:TemplateField HeaderText="Attribute"> 
     <ItemTemplate> 
     <%# ((KeyValuePair<string,string>)Container.DataItem).Key %> 
     </ItemTemplate> 
    </asp:TemplateField> 
    <asp:TemplateField HeaderText="Value"> 
     <ItemTemplate> 
     <%# ((KeyValuePair<string,string>)Container.DataItem).Value %> 
     </ItemTemplate> 
    </asp:TemplateField> 
    </Columns> 
</asp:GridView> 

해당 항목의 원하는 속성을 표시 한 후 실제 데이터 유형 (KeyValuePair)하고 있습니다.

관련 문제