Datagridview shows the length of the name instead of the name

1

I'm doing a window that shows the list of installed printers. But instead of showing the name of the printer, it shows the length of this. The code is as follows:

public partial class frmPrinters : Form
    {
        public BindingList<string> Impresoras = new BindingList<string>();
        public frmPrinters()
        {
            InitializeComponent();
        }

        private void frmPrinters_Load(object sender, EventArgs e)
        {
            BindingSource bindSource = new BindingSource();
            for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
            {
                Impresoras.Add(PrinterSettings.InstalledPrinters[i]);
            }

            bindSource.DataSource = Impresoras;
            grdPrinters.DataSource = bindSource;
        }

        private void btnCerrar_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
    
asked by ChemaPando 14.08.2017 в 21:47
source

2 answers

1

I did it in a simpler way, I do not know if it serves you, create a datatable with a string column and I add the printers, finally I link the table to the grid:

       DataTable dt = new DataTable("Impresoras");
        dt.Columns.Add(new DataColumn("nombre", typeof(string)));
        for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
        {
            dt.Rows.Add(PrinterSettings.InstalledPrinters[i].ToString());
        }
        grdPrinters.DataSource = dt;
    
answered by 14.08.2017 / 23:38
source
0

It's because the class String contains the public property Length and when you link it to your DataGridView consider it.

To solve your problem it would be necessary to implement a class that contains the information of the printer.

For example:

Class creation Impresora :

public class Impresora
{
    public string Nombre { get; set; }
}

Modify the way you get the information:

private readonly BindingList<Impresora> _impresoras = new BindingList<Impresora>();

private void Printers_Load(object sender, EventArgs e)
{
    var bindSource = new BindingSource();
    for (var i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
    {
        _impresoras.Add( new Impresora { Nombre = PrinterSettings.InstalledPrinters[i] });
    }

    bindSource.DataSource = _impresoras;
    grdPrinters.DataSource = bindSource;
}

Reference:

answered by 15.08.2017 в 16:51