2010-06-08 42 views
1

说我有一个像Dictionary<string, Dictionary<string, int>>或类似的数据结构,我想把它作为一个HTML表格作为第一个字符串键和作为第二个字符串键的列标题。有没有内置或其他控制这个?将元组呈现给ASP.NET 2.0中的表的简单方法?

+0

或者,我可以得到从数据库中的数据,如“行,列,值”的格式如果让事情更容易... – nicolaskruchten 2010-06-08 18:24:01

+0

我最终建立一个简单的控件有一个'setData(row,col,value)'方法并呈现给HTML表格。 – nicolaskruchten 2010-06-10 18:09:17

回答

3

没有内置控件可以识别这样的复杂数据结构。你需要为它做一些自定义编码。

你可以用一个带有ItemDataBound事件处理程序的Repeater轻松实现它。只是把我的头,没有测试的顶部:

<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound=" Repeater1_OnItemDataBound"> 
<ItemTemplate> 
    <asp:Literal ID="Literal1" runat="server" /> 
</ItemTemplate> 
</asp:Repeater> 


protected void Repeater1_OnItemDataBound(Object sender, RepeaterItemEventArgs e) 
{ 
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == 
      ListItemType.AlternatingItem) 
    { 
     var rowHeader= (e.Item.DataItem).Key; 
     var columnHeaders = (e.Item.DataItem).Value; 
     foreach (var header in columnHeaders) 
     { 
       // build string to populate table row, assign to Literal1 
     } 
    } 
} 
+0

是否有一个控件可以识别持有这种数据类型的另一种类型的数据结构?像上面提到的SQL结果(row,col,value)? – nicolaskruchten 2010-06-08 18:34:39

+0

不是我所知道的。您可以使用gridview识别DataRow风格的数据,因此如果您可以将元组放入DataTable中,则可以轻松地绑定到表并将HeaderTemplate处理您的头,并且行头可以位于第一列中。但是,就我所知,没有即时可用的电子表格样式控件来解析数据。 – womp 2010-06-08 18:43:34

0

您可以使用嵌套数据绑定控件并跳过OnItemDataBoundStep,只需绑定被绑定外项目的属性的内部控制。

因此,对于您的情况,您的字典中的每个项目都包含一个密钥和另一个字典。因此,每次绑定时,都可以访问该项目的字典,以将其设置为内部数据绑定控件的数据源。

请看下面的例子:

<%@ Page Language="C#" %> 

<%@ Import Namespace="System.Collections.Generic" %> 

<script runat="server"> 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     Dictionary<string, Dictionary<string, int>> TestDict = new Dictionary<string, Dictionary<string, int>>(); 


     //This is just loading the test dictionary  
     for (int i = 0; i < 10; i++) 
     { 
      Dictionary<string, int> ColData = new Dictionary<string, int>(); 

      TestDict.Add("Row Header " + i, ColData); 
      for (int j = 0; j < 5; j++) 
      { 
       ColData.Add("Col Header " + j, i + j); 
      } 
     } 

     //Bind the Outer Repeater 
     RepeaterRow.DataSource = TestDict; 
     RepeaterRow.DataBind(); 



    } 
</script> 

<html xmlns="http://www.w3.org/1999/xhtml"> 
<body> 
    <form id="form1" runat="server"> 


    <asp:Repeater ID="RepeaterRow" runat="server"> 
     <HeaderTemplate> 
      <table> 
     </HeaderTemplate> 
     <ItemTemplate> 
      <tr> 
       <th> 
        <%# Eval("Key") %> 
       </th> 
       <asp:Repeater ID="RepeaterColumn" DataSource='<%# Eval("Value")%>' runat="server"> 
        <ItemTemplate> 
         <td> 
          <%# Eval("Value") %> 
         </td> 
        </ItemTemplate> 
       </asp:Repeater> 
      </tr> 
     </ItemTemplate> 
     <FooterTemplate> 
      </table> 
     </FooterTemplate> 
    </asp:Repeater> 


    </form> 
</body> 
</html> 
相关问题