user2902617
user2902617

Reputation:

I have a simple gridview, it's not displaying data

My gridview source code is following

<asp:GridView ID="g1" runat="server"></asp:GridView>

and my code behind is,

bindGridView(ds.Tables[0], g1, lblErrorActivityGrid, lblActivityGridCount);

private void bindGridView(DataTable dt, GridView grd, Label lblError, Label GrdRowCount)
    {
        grd.DataSource = dt;
        grd.DataBind();
    }

my question is why my gridview is not displaying data? I am using dataset and manually adding data in my dataset and then returning table at 0th table.

Please help. Thanks in advance

Upvotes: 0

Views: 259

Answers (2)

afzalulh
afzalulh

Reputation: 7943

In markup set AutogenerateColumns="true" :

<asp:GridView ID="g1" AutoGenerateColumns= "true" runat="server"></asp:GridView>

Here's how I have tested your code:

In my markup I have the gridview.

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="g1" AutoGenerateColumns= "true" runat="server"></asp:GridView>
        <br />
        <asp:Label ID="lblErrorActivityGrid" runat="server" Text="Error Activity Grid"></asp:Label>        
        <br />
        <asp:Label ID="lblActivityGridCount" runat="server" Text="Activity Grid Count"></asp:Label>
    </div>
    </form>
</body>
</html>

In my code, in page load I am adding a DataTable to a DataSet and calling bindGridView method:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        dt.Columns.Add("Column1", typeof(string));
        dt.Columns.Add("Column2", typeof(string));
        ds.Tables.Add(dt);
        for (int i=0; i<5; i++)
        {
            DataRow nw = ds.Tables[0].NewRow();
            nw[0] = (i + 1).ToString();
            nw["Column1"] = (i + 1).ToString();
            nw["Column2"] = String.Format("Item {0}", i);
            ds.Tables[0].Rows.Add(nw);
        }
        bindGridView(ds.Tables[0], g1, lblErrorActivityGrid, lblActivityGridCount);
    }
}


private void bindGridView(DataTable dt, GridView grd, Label lblError, Label GrdRowCount)
{
    grd.DataSource = dt;
    grd.DataBind();
}

And here's the grid shows in my browser:

enter image description here

Upvotes: 2

Gokul E
Gokul E

Reputation: 1386

Try to Set

grd.DataSource = dt.DefaultView;

you must set the View to the Gridview from the DataTable..

Make sure the Table has Data.

Upvotes: 0

Related Questions