Wyatt Wyatt - 3 months ago 9x
Vb.net Question

VB.NET Extension Method for Gridview

I'm currently trying to set up an extension method for the gridview class so that I can get the index of a column by header text. I've found the following code in C# :

public static class ExtensionMethods
public static DataControlField GetColumnByHeader(this GridView grid, string name)
int index = -1;
for (int i = 0; i < grid.Columns.Count; i++)
if (grid.Columns[i].HeaderText.ToLower().Trim() == name.ToLower().Trim())
index = i;
return grid.Columns[index];

From http://www.softcodearticle.com/2013/06/asp-net-gridview-get-column-by-headertext/

I've researched the extension method process on MSDN, but all I can find is information on string extenders. I am very familiar with inheritance and other OOP principles, I just do not understand the exact formatting for VB.NET. Could someone explain to me the formatting for providing an extension method for the gridview class? The code inside the method is irrelevant, although I do need to be able to reference the gridview 'this' as the person in the given code does.

Any help is appreciated. Thank you.


For this you need to decorate using <Extension()>

Imports System.Runtime.CompilerServices

Module ExtensionMethods

    <Extension()> _
    Public Function GetColumnIndexByHeader(grid As GridView, name As String) As Integer
        Dim index As Integer = -1
        For i As Integer = 0 To grid.Columns.Count - 1
            If grid.Columns(i).HeaderText.ToLower().Trim() = name.ToLower().Trim() Then
                index = i
                Exit For
            End If
        Return index
    End Function

End Module

And call it like,

Dim indexOfYourHeader = GridView1.GetColumnIndexByHeader("your_header_name")

Doumentation: https://msdn.microsoft.com/en-us/library/bb384936.aspx