Using List as data source Datagridview ordered

0

Currently I have a very heavy database query that retrieves a lot of records, painting record to record in the datagrid is too slow so my solution is to retrieve the information through a datatable and then pass that datatable to a List to be able to make operations with the recovered data, the case is that I would like to show in the datagrid the fields of the list but with a certain order.

I can not find a way to assign, for example, the Column [0] of the datagrid to the Id field of the object of which the list is composed.

I regret not being able to put code because I really do not know how to do it. Greetings.

    
asked by U. Busto 23.02.2017 в 13:03
source

3 answers

2

First, why pass the DataTable to a list? Directly assign DataTable to DataSource of DataGridView .

Second, a DataGridView can autogenerate the columns, or you can define them yourself. In the second case, in each DataGridViewColumn you can define which column of DataTable is linked using the property DataPropertyName

    
answered by 23.02.2017 / 13:15
source
1

Create a class with the properties you need:

public class Clase
{
    public int Id { get; set; }
    public string Nombre { get; set; }
    public DateTime Fecha { get; set; }
}

In your method for the consult, create a list of type Class.

public void Metodo()
    {
        List<Clase> Lista = new List<Clase>();
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            using (SqlCommand command = new SqlCommand())
            {
                StringBuilder Query = new StringBuilder();

                Query.Append("SELECT * id,nombre,fecha FROM Tabla;");

                command.CommandType = System.Data.CommandType.Text;
                command.CommandText = Query.ToString();

                SqlDataReader reader = null;
                command.Connection = connection;
                connection.Open();
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    Clase obj = new Clase();
                    obj.Id = Convert.ToInt32(reader["id"]);
                    obj.Nombre = reader["nombre"].ToString();
                    obj.Fecha = Convert.ToDateTime(reader["fecha"]);
                    Lista.Add(obj);
                }
            }
        }
        DataGridView.DataSource = Lista.OrderBy(b => b.Id).ToList();
    }

You assign the DataGridView datasource to the list.

    
answered by 23.02.2017 в 17:22
1

My recommendation is that you directly save the sql query in the List here is an example:

List<Object> objects = new List<Object>();
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            using (SqlCommand command = new SqlCommand())
            {
                StringBuilder query = new StringBuilder();

                command.CommandType = System.Data.CommandType.Text;
                command.CommandText = query.ToString();

                SqlDataReader reader = null;
                command.Connection = connection;
                connection.Open();
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                        Object obj= new Object();
                        if(reader["a"] != DBNULL.Value)
                          obj.a = reader["a"];
                        objects.Add(obj);
                }
          }
       }

One way to sort the list is:

objects.Sort((x, y) => -1 * x.a.CompareTo(y.a));

-1 * does it in Descending to order ascending removes -1 *

Edit

From what I see I left the part of the presentation here is an example, you have to use AutoGenerrateColumns="False" and mount your own column structure with columns and BoundFields, as extra TemplateField that you can put whatever you want LinkButtons o Datas with% = Eval ()%

<asp:GridView ID="GridView1" Runat="server" AutoGenerateColumns="False"
    BorderWidth="1px" BackColor="White" GridLines="Vertical" 
    CellPadding="4" BorderStyle="None" BorderColor="#DEDFDE" ForeColor="Black">
    <FooterStyle BackColor="#CCCC99"></FooterStyle>
    <PagerStyle ForeColor="Black" HorizontalAlign="Right" 
       BackColor="#F7F7DE"></PagerStyle>
    <HeaderStyle ForeColor="White" Font-Bold="True" 
       BackColor="#6B696B"></HeaderStyle>
    <AlternatingRowStyle BackColor="White"></AlternatingRowStyle>
    <Columns>
        <asp:BoundField HeaderText="Titulo a mostrar" DataField="nombre de la propiedad del objeto" 
           SortExpression="nombre de la propiedad"></asp:BoundField>
        <asp:TemplateField HeaderText="Prueba">
            <ItemTemplate>
                <%# ComputeSeniorityLevel(DateTime.Now – 
                     (DateTime)Eval("HireDate")) %>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    <SelectedRowStyle ForeColor="White" Font-Bold="True" 
         BackColor="#CE5D5A"></SelectedRowStyle>
    <RowStyle BackColor="#F7F7DE"></RowStyle>
</asp:GridView>

here more information: link link

link

Everything that can be assigned from the aspx can be assigned from c # to windowsforms such that:

dgViewStudents.AutoGenerateColumns = false;
dgViewStudents.DataSource = bs;

DataGridViewColumn col = new DataGridViewTextBoxColumn();
col.DataPropertyName = "ID";
col.HeaderText = "ID Column";
col.Name = "foo";
dgViewStudents.Columns.Add(col);
    
answered by 23.02.2017 в 14:00