• Sábado 20 de Abril de 2024, 02:12

Autor Tema:  Desvincular DataGridView del origen de datos  (Leído 6058 veces)

FJCorb

  • Nuevo Miembro
  • *
  • Mensajes: 5
    • Ver Perfil
Desvincular DataGridView del origen de datos
« en: Viernes 5 de Febrero de 2010, 15:05 »
0
Tengo un DataGridView enlazado a datos: le cargo el retorno de una consulta LINQ a la propiedad DataSource.

Después agrego dinámicamente a la grid una serie columnas con datos calculados.
Me interesa ordenar la lista por estas columnas.Pero me da el error de que las columnas no enlazadas a datos no pueden ser ordenadas.

¿Se puede desenlazar la grid de la base de datos sin perder el contenido?

¿Alguna idea de cómo hacerlo?


Gracias!

eltruhanero

  • Miembro activo
  • **
  • Mensajes: 85
    • Ver Perfil
Re: Desvincular DataGridView del origen de datos
« Respuesta #1 en: Domingo 21 de Febrero de 2010, 22:24 »
0
y porq no generar la consulta LINQ ya ordenada? debe de ser mas eficiente q hacer en "codigo c#".

FJCorb

  • Nuevo Miembro
  • *
  • Mensajes: 5
    • Ver Perfil
Re: Desvincular DataGridView del origen de datos
« Respuesta #2 en: Lunes 22 de Febrero de 2010, 09:09 »
0
El problema es que en la consulta Linq no tengo toda la información.
Una vez cargada la grid, le agrego unas columnas dinámicamente cuyo contenido calculo (por código C#) en cada fila a partir de las columnas cargadas desde la base de datos. Y son estas columnas creadas a posteriori donde me interesa la ordenación.

Saludos.

eltruhanero

  • Miembro activo
  • **
  • Mensajes: 85
    • Ver Perfil
Re: Desvincular DataGridView del origen de datos
« Respuesta #3 en: Lunes 22 de Febrero de 2010, 22:30 »
0
Hola a continuacion te pongo un ejemplo de algo de lo que decis.

Lo que hago es:
Creo un conjunto de datos con 2 columnas.
Los manipulo un poco eliminando filas.
Agrego una columna mas con datos randomicos.
Ordeno todos los datos segun esa ultima columna.

El ordenamiento lo estoy haciendo con linq q me imagino es eficiente, sin embargo el hecho de quitar y agregar los DataSource puede ser ineficiente si trabajas con muuuchos datos.


Código: C#
  1.  
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Windows.Forms;
  7.  
  8. namespace WindowsFormsApplication1
  9. {
  10.     public class Form2 : Form {
  11.         private readonly Dictionary<int, int> dicRandomValues;
  12.         private int cantidadFilas = 600;
  13.  
  14.         public Form2()
  15.         {
  16.             InitializeComponent();
  17.             dicRandomValues = new Dictionary<int, int>();
  18.         }
  19.  
  20.         public object DataGridSource { get; set; }
  21.  
  22.         private void button1_Click(object sender, EventArgs e)
  23.         {
  24.             button2.Enabled = false;
  25.             dataGridView1.DataSource = null;
  26.  
  27.             // Creamos Datos ( este seria tu acceso a disco )
  28.             Dato[] datos = new Dato[cantidadFilas];
  29.             for (int i = 0; i < cantidadFilas; i++)
  30.             {
  31.                 datos[i] = new Dato(i.ToString(), i.ToString().Length);
  32.             }
  33.  
  34.             // Seleccino los que tienen largo par ( Simple tratamiento con los datos)
  35.             var myDataSource = from d in datos where d.Contenido.Last() != '1' select d;
  36.             cantidadFilas = myDataSource.Count();
  37.  
  38.             // Seteamos el resultado de ordenar como DataSource
  39.             SetGridDataSource(myDataSource);
  40.  
  41.             button1.Enabled = false;
  42.             button2.Enabled = true;
  43.         }
  44.  
  45.         private void button2_Click(object sender, EventArgs e)
  46.         {
  47.             IEnumerable<Dato> query =
  48.                 (((BindingSource)dataGridView1.DataSource).DataSource as IEnumerable<Dato>);
  49.  
  50.             if (query == null)
  51.             {
  52.                 MessageBox.Show("Primero crea las columnas");
  53.                 return;
  54.             }
  55.  
  56.             // Agregamos nueva columna
  57.             DataGridViewColumn column = CreateColumn();
  58.             dataGridView1.Columns.Add(column);
  59.            
  60.             // Agregamos los datos de la nueva columna
  61.             // En este caso inventamos numeros con CreateRandomNumber()
  62.             query = from dato in query
  63.                     select new Dato(dato.Contenido,
  64.                                     dato.Largo, CreateRandomNumber());
  65.  
  66.             //  Ordenamos segun la nueva columna
  67.             query = from dato in query.AsEnumerable()
  68.                     orderby dato.OrderBy ascending
  69.                     select dato;
  70.  
  71.             // Seteamos el resultado de ordenar como DataSource
  72.             SetGridDataSource(query);
  73.  
  74.             button2.Enabled = false;
  75.         }
  76.  
  77.         private int CreateRandomNumber()
  78.         {
  79.             int randomNumber;
  80.             do
  81.             {
  82.                 string ticksDate = DateTime.Now.Ticks.ToString();
  83.                 int seek = Convert.ToInt32(ticksDate.Remove(0, ticksDate.Length/2));
  84.                 randomNumber = new Random(seek).Next(cantidadFilas);
  85.             } while (dicRandomValues.ContainsKey(randomNumber));
  86.             dicRandomValues.Add(randomNumber, 0);
  87.             return randomNumber;
  88.         }
  89.  
  90.         private DataGridViewColumn CreateColumn()
  91.         {
  92.             return new DataGridViewTextBoxColumn
  93.                        {
  94.                            DataPropertyName = "OrderBy",
  95.                            HeaderText = "OrderBy",
  96.                            Name = "OorderBy",
  97.                        };
  98.         }
  99.  
  100.         private void SetGridDataSource(IEnumerable source)
  101.         {
  102.             dataGridView1.DataSource = null;
  103.             BindingSource binding = new BindingSource {DataSource = source};
  104.             dataGridView1.DataSource = binding;
  105.         }
  106.  
  107.         /// <summary>
  108.         /// Required designer variable.
  109.         /// </summary>
  110.         private System.ComponentModel.IContainer components = null;
  111.  
  112.         /// <summary>
  113.         /// Clean up any resources being used.
  114.         /// </summary>
  115.         /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
  116.         protected override void Dispose(bool disposing)
  117.         {
  118.             if (disposing && (components != null))
  119.             {
  120.                 components.Dispose();
  121.             }
  122.             base.Dispose(disposing);
  123.         }
  124.  
  125.         #region Windows Form Designer generated code
  126.  
  127.         /// <summary>
  128.         /// Required method for Designer support - do not modify
  129.         /// the contents of this method with the code editor.
  130.         /// </summary>
  131.         private void InitializeComponent()
  132.         {
  133.             this.components = new System.ComponentModel.Container();
  134.             this.dataGridView1 = new System.Windows.Forms.DataGridView();
  135.             this.Contenido = new System.Windows.Forms.DataGridViewTextBoxColumn();
  136.             this.Largo = new System.Windows.Forms.DataGridViewTextBoxColumn();
  137.             this.bindingSource1 = new System.Windows.Forms.BindingSource(this.components);
  138.             this.button1 = new System.Windows.Forms.Button();
  139.             this.button2 = new System.Windows.Forms.Button();
  140.             ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
  141.             ((System.ComponentModel.ISupportInitialize)(this.bindingSource1)).BeginInit();
  142.             this.SuspendLayout();
  143.             //
  144.             // dataGridView1
  145.             //
  146.             this.dataGridView1.AutoGenerateColumns = false;
  147.             this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
  148.             this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
  149.                                                                                                   this.Contenido,
  150.                                                                                                   this.Largo});
  151.             this.dataGridView1.DataSource = this.bindingSource1;
  152.             this.dataGridView1.Location = new System.Drawing.Point(28, 24);
  153.             this.dataGridView1.Name = "dataGridView1";
  154.             this.dataGridView1.Size = new System.Drawing.Size(402, 235);
  155.             this.dataGridView1.TabIndex = 0;
  156.             //
  157.             // Contenido
  158.             //
  159.             this.Contenido.DataPropertyName = "Contenido";
  160.             this.Contenido.HeaderText = "Contenido";
  161.             this.Contenido.Name = "Contenido";
  162.             //
  163.             // Largo
  164.             //
  165.             this.Largo.DataPropertyName = "Largo";
  166.             this.Largo.HeaderText = "Largo";
  167.             this.Largo.Name = "Largo";
  168.             //
  169.             // button1
  170.             //
  171.             this.button1.Location = new System.Drawing.Point(28, 303);
  172.             this.button1.Name = "button1";
  173.             this.button1.Size = new System.Drawing.Size(132, 40);
  174.             this.button1.TabIndex = 1;
  175.             this.button1.Text = "Create";
  176.             this.button1.UseVisualStyleBackColor = true;
  177.             this.button1.Click += new System.EventHandler(this.button1_Click);
  178.             //
  179.             // button2
  180.             //
  181.             this.button2.Location = new System.Drawing.Point(177, 303);
  182.             this.button2.Name = "button2";
  183.             this.button2.Size = new System.Drawing.Size(131, 42);
  184.             this.button2.TabIndex = 2;
  185.             this.button2.Text = "AddColumn";
  186.             this.button2.UseVisualStyleBackColor = true;
  187.             this.button2.Click += new System.EventHandler(this.button2_Click);
  188.             //
  189.             // Form2
  190.             //
  191.             this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
  192.             this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
  193.             this.ClientSize = new System.Drawing.Size(462, 381);
  194.             this.Controls.Add(this.button2);
  195.             this.Controls.Add(this.button1);
  196.             this.Controls.Add(this.dataGridView1);
  197.             this.Name = "Form2";
  198.             this.Text = "Form2";
  199.             ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
  200.             ((System.ComponentModel.ISupportInitialize)(this.bindingSource1)).EndInit();
  201.             this.ResumeLayout(false);
  202.  
  203.         }
  204.  
  205.         #endregion
  206.  
  207.         public DataGridView dataGridView1;
  208.         private Button button1;
  209.         private BindingSource bindingSource1;
  210.         private Button button2;
  211.         private DataGridViewTextBoxColumn Contenido;
  212.         private DataGridViewTextBoxColumn Largo;
  213.     }
  214. }
  215.  
  216.  

Espero q sirva. cualquier cosa q no entiendas pregunta.

Saludos, daniel

FJCorb

  • Nuevo Miembro
  • *
  • Mensajes: 5
    • Ver Perfil
Re: Desvincular DataGridView del origen de datos
« Respuesta #4 en: Martes 23 de Febrero de 2010, 12:34 »
0
Gracias Daniel!
Lo probaré.

Saludos