我在绑定gridview中的字典对象时面临问题。
Dictionary<string, int[]> final_list = (Dictionary<string, int[]>)Session["InstrumentBatch"];
//The data gets populated in the final_list
List<KeyValuePair<string, int[]>> kvp = new List<KeyValuePair<string, int[]>>();
kvp.AddRange(final_list);
//Adding it to a list because Dictionary is not bind able in gridview.
gvData.DataSource = kvp;
gvData.DataBind();
我应该在.aspx页面上写些什么才能在我的gridview中填充数据。欢迎任何帮助。随时提出任何问题
我想将标题显示为 instrumentType (dictionary-key(和 new,ln,pr,任何(字典值(。
。谢谢问候
好吧,这在很大程度上取决于您要在页面上显示的内容。通常,KeyValuePair公开了两个属性,钥匙和值(谁可以猜到!(,因此您可以在网格视图中使用它们。在Boundfield说:
<asp:BoundField DataField="Key" HeaderText="Key" />
<asp:BoundField DataField="Value" HeaderText="Value" />
但是,在您的情况下,这不一定按照您的期望工作,因为您的价值是一个数组。为此,您可以使用某种模板:
<asp:TemplateField HeaderText="Value">
<ItemTemplate>
<%# String.Join(",", ((int[])Eval("Value"))) %>
</ItemTemplate>
</asp:TemplateField>
使用TemplateField:
,也可以将每个列数阵列的值分开。<asp:TemplateField HeaderText="Value 0">
<ItemTemplate>
<%# ((int[])Eval("Value"))[0] %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Value 1">
<ItemTemplate>
<%# ((int[])Eval("Value"))[1] %>
</ItemTemplate>
</asp:TemplateField>
...
这是可能的。
<asp:GridView ID="GV" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Key" HeaderText="Dictionary Key" />
<asp:BoundField DataField="Value" HeaderText="Dictionary Value" />
</Columns>
</asp:GridView>
首先添加值。
Dictionary<string, int[]> final_list = (Dictionary<string, int[]>)
final_list.add(key,value);
final_list.add(key, value);
然后将其绑定,
gridview.DataSource=final_list;
gridView.DataBind();