views:

118

answers:

8

What is wrong with this c# method?

private void getMydatatable()
{
    DataTable dt = new DataTable();
    DataColumn dc;
    dc = new DataColumn("Name");
    dt.Columns.Add(dc);
    dc = new DataColumn("Age");
    dt.Columns.Add(dc);

    dt.Rows.Add("ARUN", "23");
    dt.Rows.Add("BALA", "23");
     GridView1.AutoGenerateColumns = false;
    GridView1.DataSource = dt;
    GridView1.DataBind();
    Page.Controls.Add(GridView1);
}

This method gets called on page load but my gridview is invisible why?

<form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="DlUser" runat="server">
        </asp:DropDownList>

        <asp:CheckBoxList ID="ChkUser" runat="server">
        </asp:CheckBoxList>
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
    </div>
</form>
+1  A: 

You sure it's invisible? Don't you have to add it to the form?

Mark
+1  A: 

I'm assuming this is ASP.NET. You create a new GridView :

 GridView gv = new GridView();

and give it some data, but in the snippet here you never actually put it on the page. So it goes out of scope when this function exits, the GC cleans it up, and no one ever sees it...

AakashM
+4  A: 

You need to add the GridView to the page or the gv instance you are creating will be garbage collected as soon as you leave this method:

Page.Controls.Add(gv);
Darin Dimitrov
@Darin: just like this, people too often tend to forget to write cookies in the Response and just create them only. Then they wonder why next Request has no cookies. :)
this. __curious_geek
@darin Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.
MuraliVijay CSK
@MuraliVijay CSK, after the modification in your code you no longer need to add `GridView1` to the page as it is already there.
Darin Dimitrov
+1  A: 

you declared

GridView gv = new GridView(); 

in the scope of your method. you'd better make it a member of your GUI class and add in in controls container

Page.Controls.Add(gv); 

or do it by means of GUI editor

Arseny
+2  A: 

Seems your GridView is not in Page Controls. In other words GridView is not on page.

You need to add it like this.

Page.Controls.Add(gv); 
Incognito
+1  A: 

You're not adding the GridView to the page at all. The GridView you created, gv, immediately falls out of scope at the end of the getMydatatable() method.

Winston Smith
A: 

The markup specifies GridView1, so with that (updated) code sample you don't need to add it again. But if you do not autogenerate columns you should specify them in markup. Or tell the grid to auto generate the columns ...

Sascha
A: 

The gridview is showing, but because you put AutoGenerateColumns to false, it doesn't actually render anything. Also you need to remove this line.

Page.Controls.Add(GridView1);
Johann Strydom