Reputation: 360
My home page is displaying images slideshow using jquery,all these images are retrieving from mysql during the run time.I have created 9 images inside the division which are moving by jquery and i am giving the value of image url from codebehind.please see my code below,if database contains lesser than 9 images,null image should be hidden.how can i do it?
<a href="#">
DataTable dt = Db.ids("home_table");
Image1.ImageUrl = "~/Handler1.ashx?id=" + Convert.ToInt16(dt.Rows[0]["id"].ToString());
Image2.ImageUrl = "~/Handler1.ashx?id=" + Convert.ToInt16(dt.Rows[1]["id"].ToString());
This method is followed for all 9 images...
Upvotes: 0
Views: 306
Reputation: 70513
Two ways to solve.
Easy way:
You can create a static array of your Image controls (an array with 9 elements) then in a loop from zero to number of images-1. You then de-reference into that array to change the url. Should look like this (example code, non-compiled, might have bugs or typos)
Decl:
Image imageArray[] = { Image1, Image2 ... , Image9};
In the loop:
imageArray[index].ImageUrl = "~/Handler1.ashx?id=" + Convert.ToInt16(dt.Rows[index]["id"].ToString());
Or the hard way:
Dynamically add image controls to the page.
Upvotes: 0
Reputation: 8920
You get an error because you directly access rows that do not exist. You need to count the numbers of rows in your DT.
numberOfRows = dt.Rows.Count
And after that
if ( numberOfRows >= 2 )
{
Image2.ImageUrl = "~/Handler1.ashx?id=" + ... }
if ( numberOfRows >= 3 )
{
Image3.ImageUrl = "~/Handler1.ashx?id=" + .... }
etc.
Upvotes: 2
Reputation: 103338
You can't concatenate a string and an integer:
Image1.ImageUrl = "~/Handler1.ashx?id=" + Convert.ToInt16(dt.Rows[0]["id"]);
Convert ToString()
to resolve:
Image1.ImageUrl = "~/Handler1.ashx?id=" + Convert.ToInt16(dt.Rows[0]["id"]).ToString();
Upvotes: 2