Juste3alfaz Juste3alfaz - 1 month ago 24
ASP.NET (C#) Question

error Showing Data asp.net WebForms

I try to get data from Database, I am using ado.net.
I am using a tutorial,and it works with another page contains relation between 2 classes.
But with this I am facing problem to get all data, and I already have data in database.
this is my code :

private void PopulateClients()
{
List<Client> allClients = null;
using (MyDataBaseEntities dc = new MyDataBaseEntities())
{
var clients = (from a in dc.Clients
select new
{
a
});
if (clients != null)
{
allClients = new List<Client>();
}

if (allClients == null || allClients.Count == 0)
{
//trick to show footer when there is no data in the gridview
allClients.Add(new Client());
myGridview.DataSource = allClients;
myGridview.DataBind();
myGridview.Rows[0].Visible = false;
}
else
{
myGridview.DataSource = allClients;
myGridview.DataBind();
}
}
}


I see this tutorial


Solution


private void PopulateClients()
{
List<Client> allClients = null;
using (MyDataBaseEntities dc = new MyDataBaseEntities())
{
var clients = (from a in dc.Clients
select new
{
a
});
if (clients != null)
{
allClients = new List<Client>();
foreach (var i in clients)
{
allClients.Add(i.a);
}
}

if (allClients == null || allClients.Count == 0)
{
//trick to show footer when there is no data in the gridview
allClients.Add(new Client());
myGridview.DataSource = allClients;
myGridview.DataBind();
myGridview.Rows[0].Visible = false;
}
else
{
myGridview.DataSource = allClients;
myGridview.DataBind();
}
}
}

Answer

You are getting no data because you don't use the data fecthed from the query (that are inside IEnumerable<Clients> clients).
You just check that clients is different from null and then you create another istance of List<Clients> and after all you bind allClients that it's clearly empty.

            var clients = (from a in dc.Clients
                                select new
                                {
                                    a
                                }).ToList();
            if (clients != null && clients.Any())
            {
                myGridview.DataSource = clients;
                myGridview.DataBind();
                myGridview.Rows[0].Visible = false;
            }
            else
            {
                myGridview.DataSource = clients;
                myGridview.DataBind();
            }