简体   繁体   中英

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;
                break;
            }
        }
        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.

In VB.NET you have to use the attribute manually.

Imports System.Runtime.CompilerServices

Module MyExtensions

    <Extension> _
    Public Function MyExtensionMethod(ByVal grid As GridView, ByVal name As String) As DataControlField

        ' ... your code here!

    End Function

End Module

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
        For i As Integer = 0 To grid.Columns.Count - 1
            If grid.Columns(i).HeaderText.ToLower().Trim() = name.ToLower().Trim() Then
                Return i
            End If
        Next
        Return -1
    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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM