Вопрос по asp.net, vb.net – Привязать словарь к GridView

3

Ссылаясь на эту тему:Алгоритм подсчета времени, произошедшего за тот же периодКак привязать словарь к GridView? Просьба взглянуть на ответ.

Я попытался добавить GridView, а затем на код позади:GV.DataSource = timeRangeCounts и связать его, но взамен

The data source for GridView with id 'GV' did not have any properties or attributes from which to generate columns. Ensure that your data source has content.

Как я могу это сделать? Пожалуйста, посмотрите на код ниже:

Первый вспомогательный класс используется для хранения количества точных совпадений и совпадений поддиапазона:

Public Class TimeRangeCounter
    Property ExactRangeMatch as Integer
    Property SubRangeMatch as Integer
End Class

Второй вспомогательный класс используется, чтобы помочь словарю узнать, как один ключ (типаTimeRange) отличается от другого:

Public Class TimeRangeEqualityComparer 
    Implements IEqualityComparer(Of TimeRange)

    Public Overloads Function Equals(left As TimeRange, right As TimeRange) _
            As Boolean Implements IEqualityComparer(Of TimeRange).Equals           

        Return left.ToString = right.ToString   
    End Function

    Public Overloads Function GetHashCode(range As TimeRange) _
            As Integer Implements IEqualityComparer(Of TimeRange).GetHashCode

        return range.ToString().GetHashCode()
    End Function

End Class

Третий вспомогательный класс хранит время начала и окончания диапазона:

Public Class TimeRange 
    Private readonly _start
    Private readonly _end

    Public Readonly Property Start 
        Get
           return _start
        End Get
    End Property

    Public Readonly Property [End] 
        Get
           return _end
        End Get
    End Property

    Public Sub New(start As String, [end] As string)
        Me._start = start
        Me._end = [end]
    End Sub

    Public Overrides Function ToString() as String
       Return String.Format("{0}-{1}", Start, [End])
    End Function

End Class

Таким образом, используя вышеизложенное, мы должны написать этот алгоритм:

Dim columnLength As Integer = 5
Dim timeStart() As String = {"08.00", "08.00", "10.00", "08.00", "08.00"}
Dim timeEnd() As String = {"08.50", "11.50", "11.00", "09.00", "08.50"}
Dim comparer As New TimeRangeEqualityComparer()
Dim timeRangeCounts As New Dictionary(Of TimeRange, TimeRangeCounter)(comparer)

'Count exact range matches while building dictionary
For i = 0 to columnLength - 1
  Dim key As TimeRange = New TimeRange(timeStart(i), timeEnd(i))

  If timeRangeCounts.ContainsKey(key)
      timeRangeCounts(key).ExactRangeMatch += 1
  Else
      Dim counter =  New TimeRangeCounter()
      counter.ExactRangeMatch = 1
      timeRangeCounts(key) = counter
  End If        

Next           

'Count sub ranges          
For Each kvp in timeRangeCounts
    For Each key in timeRangeCounts.Keys
        If kvp.key.Start >= key.Start AndAlso _ 
           kvp.Key.End <= key.End AndAlso _
           kvp.key.ToString <> key.ToString then           

            kvp.Value.SubRangeMatch += 1
        End If
    Next
Next

'Console.WriteLine(timeRangeCounts)
    GV.DataSource = timeRangeCounts
    GV.DataBind()

Вид сетки:

<asp:GridView ID="GV" runat="server">
    <Columns>
        <asp:BoundField DataField="Key" HeaderText="Dictionary Key" />
        <asp:BoundField DataField="Value" HeaderText="Dictionary Value" />
    </Columns>
</asp:GridView>

Затем я попытался запустить его, но результат выглядит так:

Dictionary Key    Dictionary Value
08:00:00-08:50:00 TimeRangeCounter
08:00:00-09:40:00 TimeRangeCounter
10:00:00-11:40:00 TimeRangeCounter
...               ...

Что не так с кодом?

Error: User Rate Limit ExceededToString()Error: User Rate Limit Exceeded Brian Webster
Error: User Rate Limit Exceeded Brian Webster
Error: User Rate Limit Exceeded Brian Webster
Error: User Rate Limit ExceededTimeRangeCounter. mrjimoy_05

Ваш Ответ

1   ответ
5

Here is a Gridview

    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>

Here is code to bind a dictionary to that Gridview

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim D As New Dictionary(Of Integer, String)
    D.Add(1, "One")
    D.Add(2, "Two")
    D.Add(3, "Three")
    GV.DataSource = D
    GV.DataBind()
End Sub

Here is the output

enter image description here

What if my Value of of some type "MyClass?"

Error: User Rate Limit ExceededToStringError: User Rate Limit ExceededMyClassError: User Rate Limit Exceeded

Error: User Rate Limit ExceededToStringError: User Rate Limit Exceeded

Public Class TimeRangeCounter
    Property ExactRangeMatch as Integer
    Property SubRangeMatch as Integer
End Class

Error: User Rate Limit ExceededTimeRangeCounter

Summary

Error: User Rate Limit Exceeded

Problem 1 was generating an actual error and was solved by following my code example Problem 2 was the lack of a ToString function for the custom class used in the "Value" column of the Gridview
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded mrjimoy_05
Error: User Rate Limit Exceededstackoverflow.com/questions/9975788/…Error: User Rate Limit Exceeded mrjimoy_05

Похожие вопросы