nitinvertigo
nitinvertigo

Reputation: 1180

How to dynamically add gridviews side by side using asp.net c#

I am creating a page which shows some details in several gridviews. I am saying several because the number of gridviews is not constant. I am having a panel on the aspx page and adding gridviews to it dynamically.

aspx code:

<asp:Panel ID="pnlResult" runat="server"></asp:Panel>

aspx.cs code

int numOfGroups = some number here;
            for (int i = 1; i < numOfGroups + 1; i++)
            {
                GridView grd = new GridView();
                grd.ID = "GridView" + i.ToString();
                grd.BackColor = getColor(i);
                grd.DataSource = dt; // some data source
                grd.DataBind();
                pnlResult.Controls.Add(grd);
            }

But my problem is that the gridviews are adding one below the another . I want them to be side by side. How can I achieve that?

Note: Panel is not mandatory. Anything else can be used in its place

Upvotes: 0

Views: 6048

Answers (4)

Habib
Habib

Reputation: 223392

You have to float your elements inside the panel to left. To achieve that in your code behind, before adding grid to the panel do:

grd.Attributes.Add("class", "float-left");

Where float-left class in your css is defined as:

.float-left {
    float: left;
}

So your code would look like:

for (int i = 1; i < numOfGroups + 1; i++)
{
    GridView grd = new GridView();
    grd.ID = "GridView" + i.ToString();
    grd.BackColor = getColor(i);
    grd.Attributes.Add("class", "float-left"); //here
    grd.DataSource = dt; // some data source
    grd.DataBind();
    pnlResult.Controls.Add(grd);
}

Upvotes: 2

prasy
prasy

Reputation: 260

You can do something like this

Table tbl = new Table();
TableRow tr = new TableRow();
TableCell tc = new TableCell();

btn = new  Button();
        btn.Text = "Add ";
        btn.Height = Unit.Pixel(30);
        btn.Width = Unit.Pixel(100);

tc.Controls.Add(btn);

tr.Controls.Add(tc);
tbl.Controls.Add(tr);
panel.Controls.Add(tbl);

Upvotes: 1

Den
Den

Reputation: 71

Maybe u need just to add some css? like that:

grd.DataSource = dt; // some data source grd.Style["float"] = "left"; // css grd.DataBind();

Upvotes: 1

Brian Mains
Brian Mains

Reputation: 50728

If you use a table control, then you can create a row, and add each grid as cells, which would enforce the side-by-side requirement:

TableCell cell = new TableCell();
cell.Controls.Add(grd);

table.Rows(0).Cells.Add(cell);

Something like that; not sure if the Table API example above is 100% correct, but hopefully you get the idea.

Upvotes: 1

Related Questions