Error creating extension for DataGridView C #?

1

I have already used extensions for other components and did not give this problem, you are giving error only with DataGridView . The component finds the extension, not the error, the error only displays when compiling the project.

When compiling is giving the following error :

  

Error 1 'System.Windows.Forms.DataGridView' does not contain a definition for 'GetColumnName' and no extension method 'GetColumnName' accepting a first argument of type 'System.Windows.Forms.DataGridView' could be found (are C: \ Users \ Nicola Bogar \ Desktop \ System \ MySolutionApp \ WindowsFormsApplication3 \ frmCadastroPais.cs 55 38 WindowsFormsApplication3

public static class ExtensionsDataGridView
{
    /// <summary>
    /// Obter os nomes das colunas da DataGridView.
    /// </summary>
    /// <param name="dgv"> Grid.</param>
    /// <returns> Lista com os nomes das colunas. </returns>
    public static List<string> ObterNomeDasColunas(this DataGridView dgv)
    {
        List<string> lista = new List<string>();

        if (dgv == null)
            return null;

        if (dgv.ColumnCount > 0)
            for (int i = 0; i < dgv.ColumnCount; i++)
                lista.Add(dgv.Columns[i].Name);
        return lista;
    }
}

public class Teste
{
   private void frmCadastroPais_Load(object sender, EventArgs e)
   {
      DataGridView dgv = new DataGridView();
      dgv.DataSource = paisBindingSource.DataSource;

      List<string> lista = dgv.ObterNomeDasColunas();
   }
}
    
asked by anonymous 01.06.2017 / 18:45

1 answer

0

Your error in question is that the corresponding namespace of the extension method is not found or some very particular error, so I will generate a minimum example for that you try and solve your problem:

Try this:

using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace GridExtensions
{
    public static class Utils
    {
        public static IEnumerable<string> GetNamesFromColumns(this DataGridView grid)
        {
            if (grid != null && grid.Columns != null && grid.Columns.Count > 0)
            {
                return (grid.Columns as BaseCollection)
                    .OfType<DataGridViewColumn>()
                    .Select(x => x.Name).ToList();
            }
            return null;
        }
    }
}
Note: does not often need to generate a for to extract information where the base is always collections and #

using GridExtensions; // namespace respectivo do método de extensão...

public class Teste
{
   private void frmCadastroPais_Load(object sender, EventArgs e)
   {
      DataGridView dgv = new DataGridView();
      dgv.DataSource = paisBindingSource.DataSource;

      List<string> lista = dgv.GetNamesFromColumns();
   }
}
    
01.06.2017 / 23:47