I want to populate GridView below with images:
<asp:GridView ID="GrdDynamic" runat="server" AutoGenerateColumns="False">
<Columns>
</Columns>
</asp:GridView>
The code below iterates through directory, then I collect image titles and want them to be populated in gridview. code in bold is not working well, gridview is only filled with the last image in list.
List<string> imagelist = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
foreach (String image in Directory.GetFiles(Server.MapPath("example/")))
{
imagelist.Add("~/example/" + Path.GetFileName(image));
}
loadDynamicGrid(imagelist);
}
private void loadDynamicGrid(List<string> list)
{
DataTable dt = new DataTable();
DataColumn dcol = new DataColumn(NAME, typeof(System.String));
dt.Columns.Add(dcol);
dcol = new DataColumn("NAME1", typeof(System.String));
dt.Columns.Add(dcol);
dcol = new DataColumn("NAME2", typeof(System.String));
dt.Columns.Add(dcol);
dcol = new DataColumn("NAME3", typeof(System.String));
dt.Columns.Add(dcol);
DataRow drow = dt.NewRow();
dt.Rows.Add();
dt.Rows.Add();
**for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
foreach (string value in list)
{
dt.Rows[i][j] = value;
}
}
}**
foreach (DataColumn col in dt.Columns)
{
ImageField bfield = new ImageField();
bfield.DataImageUrlField = NAME;
bfield.HeaderText = col.ColumnName;
GrdDynamic.Columns.Add(bfield);
}
GrdDynamic.DataSource = dt;
GrdDynamic.DataBind();
}
how to fill gridview cell-by-cell only with available amount of images?
i know it is easy, i tried various methods like: dt.Rows.Add(list); and some other attempts, but they didn’t work. i’m very stupid.
i’d be glad for any help.
You’re repeatedly setting every cell to every string with your
foreach. You need to addess a specific element inlistthat will correspond to the specific cell. Try something like this:Edit: Reading your question more carefully, your problem is fundamentally outside of that loop. Even if you applied the above fix, you still wouldn’t get what you’re hoping for. What you need to do is loop over the list, and add each item in the list a row, and add that row to the table. Something like this: