-1

I have this code:

public void llenarDGVChoferes (string _comando)
{
    //ComandoSQL para el dgvChoferes
    var comando = _comando;
    var datosConexion = new SqlConnection(stringconection); // Your Connection String here
    //ComandoSQL para el dgvClientes
    var dataAdapter = new SqlDataAdapter(comando, datosConexion);
    var commandBuilder = new SqlCommandBuilder(dataAdapter);
    var ds = new DataSet();
    dataAdapter.Fill(ds);
    dgvChoferes.ReadOnly = true;
    dgvChoferes.DataSource = ds.Tables[0];
    dgvChoferes.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
}

Which you pass the SQL query in te _comando parameter and it fill the DataGridView called dgvChoferes with the query's result. This method works fine, but i'd like to know if there is any way to pass the DataGridView's name in the method's parameter. Something like this (pseudo-code)

    public void llenarDGVChoferes (string _comando, dgvName) //dgvName = DataGridView's name
{
    //ComandoSQL para el dgvChoferes
    var comando = _comando;
    var datosConexion = new SqlConnection(stringconnection); // Your Connection String here
    //ComandoSQL para el dgvClientes
    var dataAdapter = new SqlDataAdapter(comando, datosConexion);
    var commandBuilder = new SqlCommandBuilder(dataAdapter);
    var ds = new DataSet();
    dataAdapter.Fill(ds);
    dgvName.ReadOnly = true;
    dgvName.DataSource = ds.Tables[0];
    dgvName.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
}

So I'll be able to fill any DataGridView with this method.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
AtarC5
  • 393
  • 2
  • 11
  • 27
  • By adding a parameter `DataGridView dataGridView` and providing that at the call site. – CodeCaster Feb 26 '17 at 22:48
  • @CodeCaster That works! Thank you a lot! – AtarC5 Feb 26 '17 at 22:55
  • 1
    See the marked duplicate for a discussion on how parameter passing works, including how you can pass a reference type like `DataGridView` by-value and still modify its properties as you want to do here (i.e. you just pass the object, like any other value). See also http://www.yoda.arachsys.com/csharp/parameters.html for more discussion (as suggested in comment in the marked duplicate), and other related Q&A like https://stackoverflow.com/questions/1750070/datagridview-pass-by-value-or-reference and https://stackoverflow.com/questions/18787530/passing-reference-type-in-c-sharp – Peter Duniho Feb 26 '17 at 23:05
  • @PeterDuniho Excuse me, i made that question becaus i couldn't understand those posts that you recommended me. Anyway, thanks for answering! – AtarC5 Feb 26 '17 at 23:39

1 Answers1

0

Yes, simply by specifying:

public void llenarDGVChoferes(string _comando, DataGridView dgvName)

Wim
  • 11,998
  • 1
  • 34
  • 57