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

僤鯓⒐⒋嵵緔 提交于 2019-12-13 21:27:49

问题


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


回答1:


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);
}



回答2:


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.




回答3:


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

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




回答4:


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);


来源:https://stackoverflow.com/questions/27275502/how-to-dynamically-add-gridviews-side-by-side-using-asp-net-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!