top of page

CARGAR UN LISTVIEW CON INFORMACION DE UNA TABLA SQL SERVER CON C#

Código simple para exportar una tabla o consulta de SQL SERVER a un LISTVIEW

El código es el siguiente.

//librerias

using System;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;

public string LlenarListView(string id, ListView elListview)

        {
            string ipServidor = "192.168.xxx.xxx";
            string elUsuario = "myuser";
            string elpw = "mypw";


            DataTable dt = new DataTable();
            SqlConnection con = new SqlConnection();
            con = new SqlConnection("data source=" + ipServidor + ";uid =" + elUsuario +
                            "; PWD=" + elpw + "; initial catalog= miBasededatos");

            string textoCmd = "select CELULA, [Azimuth],NOMBRE from [dbo].[View_CELDAS] where torre like '" +
                id + "%' or nombre like '" + id + "%' ORDER BY AZIMUTH";

            try
            {
         
      con.Open();
                SqlCommand cmd = new SqlCommand(textoCmd, con);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);

                //LIMPIAR LIST VIEW PARA LA NUEVA CONSULTA
                elListview.Clear();

                //DEFINIR FORMATO DE LINEAS AL LIST VIEW
                elListview.View = View.Details;
                elListview.GridLines = true;
                elListview.FullRowSelect = true;

                //ASIGNAR COLUMNAS, RESPECTIVOS NOMBRES Y TAMAÑOS DE RENGLÓN
                elListview.Columns.Add(dt.Columns[0].ToString(), 70);
                elListview.Columns.Add(dt.Columns[1].ToString(), 70);
                elListview.Columns.Add(dt.Columns[2].ToString(), 280);

                foreach (DataRow renglon in dt.Rows)
                {

                    string[] arr = new string[3];
                    ListViewItem itm = new ListViewItem();


                    //ADICIONAR ITEM AL LISTVIEW                   

                    for (int ncolumna = 0; ncolumna < 3; ncolumna++)
                    {
                   
    arr[ncolumna] = renglon[ncolumna].ToString();
                        itm = new ListViewItem(arr);

                    }
               
    elListview.Items.Add(itm);
                }

                return "";
            }
            catch (Exception e)
            {
           
    return e.Message;
            }
            finally
            {
             
  con.Close();
            }
        }

bottom of page