Using VB.NET I am trying to display an arraylist in a gridview. I am having a few problems:
-Doing the DataBind above is adding an extra column to my gridview which I do not want. How can I stop this from being visible? I only want to show the column defined in the aspx file.
-The Delete button is not matching up with the selected row. When defining the 'varOldName' in the below code, it is showing me the error message 'Object reference not set to an instance of an object.' Can anyone show me what I am doing wrong here?
<asp:GridView ID="gvNames" runat="server"
OnRowDeleting="gvNames_SelectedIndexChanged"
AllowSorting="true"
OnSorting="TaskGridView_Sorting">
<columns>
<asp:TemplateField HeaderText="Names" SortExpression="true">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Container.DataItem %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="true" />
</columns>
</asp:GridView>
Public Sub GetDataForGrid(Optional ByVal varNewName As String = "", Optional ByVal varOldName As Integer = -10)
Try
'Create an in-memory collection of 4 Person objects
Dim lstNameList As ArrayList = New ArrayList
lstNameList.Add("First Second")
lstNameList.Add("One Two")
lstNameList.Add("Three Four")
lstNameList.Add("Five Six")
'Loop through each arraylist item to manipulate the name string for display
Dim lstNameListReverse As ArrayList = New ArrayList
For i As Integer = 0 To lstNameList.Count - 1
Dim FirstName As String = lstNameList(i).ToString.Substring(0, lstNameList(i).IndexOf(" "))
Dim LastName As String = lstNameList(i).ToString.Substring(lstNameList(i).IndexOf(" ") + 1)
Dim FullName As String = LastName + "," + FirstName
lstNameListReverse.Add(FullName)
Next
'Bind the data to the gridview
gvNames.DataSource = lstNameListReverse
gvNames.DataBind()
gvNames.Columns.Item(2).Visible = True
'Put the arraylist in a session value
Session("MyArrayListData") = lstNameListReverse
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Protected Sub gvNames_SelectedIndexChanged(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
Try
Dim lstListToRemoveFrom As ArrayList = Session("MyArrayListData")
Dim varNewName As String = ""
Dim varOldName As Integer = gvNames.SelectedRow.DataItem
GetDataForGridSession(varNewName, varOldName)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub