I am trying to add dynamically gridview (headerstylewidth, back-color, height, etc…, itemstyle width, back-color, height, etc…), in codebehind but I am receiving this error:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
See the code:
<asp:GridView
runat ="server"
ID="gridview1"
Height="175px"
Width="750px"
GridLines="Both"
onRowDatabound="gvdata_onRowdataBound">
<Columns >
</Columns >
</asp:GridView>
Private Sub getnum()
Dim fullnum As String = TextBox.Text.Trim()
Dim HttpClient As HttpResponseMessage = client.GetAsync(Convert.ToString("api/allnumbers? Numbers=") & fullnum).Result
If HttpClient.IsSuccessStatusCode Then
Dim fnum = HttpClient.Content.ReadAsAsync(Of IEnumerable(Of descriptNumbers))().Result
'Create Table Manually
Dim dt As New DataTable()
'Add Columns to DataTable
dt.Columns.Add("Number", GetType(String))
dt.Columns.Add("Type", GetType(String))
dt.Columns.Add("Description", GetType(String))
dt.Columns.Add("Value", GetType(String))
For Each info In Numbers
Dim dr As DataRow = dt.NewRow()
dr("Number") = info.pxNumber
dr("Type") = info.pxtype
dr("Description") = info.pxValue
dr("Value") = info.descType
dt.Rows.Add(dr)
Next
Gridview1.DataSource = dt
Gridview1.DataBind()
ERROR HAPPENS HERE:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Gridview1.Columns(0).ItemStyle.Width = Unit.Pixel(75)
Gridview1.Columns(0).HeaderStyle.Width = Unit.Pixel(75)
Gridview1.Columns(0).HeaderStyle.BackColor = Drawing.Color.Gray
Gridview1.Columns(0).HeaderStyle.ForeColor = Drawing.Color.white
Gridview1.Columns(1).ItemStyle.Width = Unit.Pixel(45)
Gridview1.Columns(1).HeaderStyle.Width = Unit.Pixel(45)
Gridview1.Columns(1).HeaderStyle.BackColor = Drawing.Color. Gray
Gridview1.Columns(1).HeaderStyle.ForeColor = Drawing.Color.white
Gridview1.Columns(2).ItemStyle.Width = Unit.Pixel(55)
Gridview1.Columns(2).HeaderStyle.Width = Unit.Pixel(55)
Gridview1.Columns(2).HeaderStyle.BackColor = Drawing.Color. Gray
Gridview1.Columns(2).HeaderStyle.ForeColor = Drawing.Color.white
Gridview1.Columns(3).ItemStyle.Width = Unit.Pixel(225)
Gridview1.Columns(3).HeaderStyle.Width = Unit.Pixel(225)
Gridview1.Columns(3).HeaderStyle.BackColor = Drawing.Color. Gray
Gridview1.Columns(3).HeaderStyle.ForeColor = Drawing.Color.white
End Sub
Protected Sub gvdata_OnRowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Cells(0).BackColor = Drawing.Color.LightBlue
e.Row.Cells(0).Font.Size = 10
e.Row.Cells(0).ForeColor = Drawing.Color.Red
e.Row.Cells(0).HorizontalAlign = HorizontalAlign.Right
End If
End Sub