Guide on programmatically integrating images into the user interface in ASP.NET from the code behind, while ensuring that all styles have been pre-defined in the .as

I have created a static aspx page with the following code:

<div class="container">
    <div class="contain" id="subdiv" runat="server">

  <input type="checkbox" id="cb1" runat="server" />

    <label for="cb1">

        <img src="Images/download_image.jfif" runat="server" id="imagesrc"/>
           <label>some text</label>  

            </label>

 </div>
       </div>

Currently, I only have one image on the UI and I'm attempting to manually increase the count like this:

for (int i = 0; i <= 5; i++)
{
    Image img = new Image();
    img.ImageUrl = "~/Images/download_image.jfif";         
    subdiv.Controls.Add(img);
}

The code above is not working. The images are supposed to act like checkboxes with label captions. However, the number of images should be based on data from a SQL table, and all images are the same. How can I access the image inside the div element and display it based on the count from the code behind so that all CSS and JS scripts will still be applied? Any help would be appreciated.

Answer №1

In order to retrieve data from a database, it is recommended to utilize the OdbcCommand. Below is an example of how you can incorporate this into your code:

 using (OdbcCommand cmd = new OdbcCommand(yourquery, cn))
            {
                using (OdbcDataReader reader = cmd.ExecuteReader())
                {
                    var divHtml = new System.Text.StringBuilder();
                    while (reader.Read())
                    {
                        System.Web.UI.HtmlControls.HtmlGenericControl div = new 
                        System.Web.UI.HtmlControls.HtmlGenericControl("div");
                        div.ID = "div";
                        div.InnerHtml = String.Format("{0}", reader.GetString(0));
                        Image img = new Image();
                        img.ImageUrl = "~/Images/download_image.jfif";
                        img.AlternateText = "Dynamic Images";
                        div.Controls.Add(img);
                        divHtml.append(div);
                    }
                    subdiv.InnerHtml = divHtml.ToString();
                }
            }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Connecting to PostgresSql through Web Services

Currently, I am in the process of developing an iOS application and integrating a PostgreSql database. My goal is to establish web services that can communicate with the database for data retrieval and insertion purposes. For instance, I aim to set up a we ...

Tips for including a horizontal line beneath each heading in an HTML using just CSS

Is it possible to include a horizontal line following each heading without employing the <hr> tag? I am interested in accomplishing this solely within the parameters of the <style></style> tags. ...

Two separate forms displayed on a single page in ASP.NET MVC 5

I have a website built using ASP MVC 5 that contains two forms. Screenshot of the page The first form, "LoginPanel," is a Partial View structured like this: @model UowTest.Models.LoginPanelModel @using (Html.BeginForm("LoginPanel", "Account", FormMethod ...

Can JavaScript be used to adjust the zoom level of a website when the user's display scaling is set above 100%, like at 125% or 150%?

These are the display settings I was referring to... They are always set to 150% on laptops... Is it possible to adjust the website zoom using javascript if the user has display settings scaling above 100%, such as 125% or 150%? ...

Increasing the Efficiency of Styled Components

It appears to me that there is room for improvement when it comes to checking for props in Styled Components. Consider the following code: ${props => props.white && `color: ${colors.white}`} ${props => props.light && `color: ${c ...

Utilize $http.get within a service/factory to retrieve a set of items

I am trying to utilize a http.get promise within an angularjs service, perform some manipulation on the retrieved collection, and then pass it back to a controller... My query is regarding the proper usage of $http.get() in a service to fetch and modify t ...

Monitoring changes in SASS files using node-sass through NPM

I have node-sass installed with the options set according to the guidance provided in a response on Using node-sass watch option with npm run-script, however, I am facing issues with it not working as expected. Below is the content of my package.json file ...

Implementing a validator based on the operator selection in react-querybuilder

Is it possible to add validators to fields that are only active when using the like operator? For example, if the like or unlike operators are used in the phoneNumber field without the % sign, it should be invalid. If the = operator is used, the % sign sho ...

Executing processes individually within AngularJS

Just making sure I understand correctly, I have a simple web service resource query function set up like this //Get country lists $scope.getCountry = function(){ $http({ method : 'GET', url : cdnLinks('country&apos ...

Is it necessary to integrate the Facebook JavaScript SDK even if I do not plan on utilizing its features?

I have created some simple applications to use as custom tabs on my Facebook page, consisting of hyperlink images. I am not utilizing any of the functionality provided by the Facebook JavaScript SDK in these instances. Do I really need to load the Faceboo ...

JavaScript does not function properly with dynamically loaded content

Trying to load the page content using the JQuery load() method. See below for the code snippet: $(window).ready(function() { $('#content').load('views/login.html'); }); .mdl-layout { align-items: center; justify-content: center ...

Oops! There was an error: Uncaught promise rejection: TypeError - Unable to access 'subscribe' property of null object (Ionic Angular)

I encountered an issue in my angular ionic project. When I log in, the first page displays the error "ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'subscribe' of null." However, upon reloading the page, the error disappears ...

Utilize AJAX to securely transmit solely $_POST variables to PHP, omitting any HTML responses

Seeking to solely transfer $_POST's variables (variables from the $_POST array) into a PHP file via AJAX call without displaying any success messages like alert('ok, it's fine') or $('blah').text('done it!'). My goal ...

Why am I unable to choose an element by its Id?

My goal is to pass an ID as an argument to a function in the following manner: HTML <button type="button" class="like btn" onclick="like('<%=postid%>')"> <svg id ='<%=likei ...

Display the chosen option in the console by using onChange() function; this is analogous to how onSelect()

I'm having trouble getting the value of a select element to log in the console. I managed to do this with an onSelect() method, but the onChange() method isn't returning anything. Here's what I tried with the onChange() method: <Form.Gr ...

What is the outcome of using VueUse.useMouse() if it is not made reactive?

Whenever I use VueUse.useMouse(), the results in console.log() change as I move the mouse. However, the results within <span></span> always remain 0. This is quite confusing to me, can someone please explain why this is happening? ...

Guide to setting up a Node, Express, Connect-Auth, and Backbone application architecture for server-side development

As someone who primarily works on the client-side, I have recently ventured into the realm of server-side JavaScript. My initial plan for my first Node.js application involves a server-side setup that primarily serves an empty shell along with a plethora o ...

Hover-over div's to switch them on

I am faced with a challenge involving a UL list structured like this: <ul> <li id="firstdiv">First div</li> <li id="seconddiv">Second div</li> <li id="thirddiv">Third div</li> .... </ul> Below the list, the ...

What is the best way to shorten a tweet that goes over 140 characters?

I have an algorithm for tweeting that eliminates @-mentions and will not post tweets under the following conditions: 1) if the question is different from the answer, 2) if the composed tweet exceeds 140 characters, and 3) if the tweet is potentially sensit ...

What is the best way to automatically resize images in Bootstrap thumbnails?

<div class="container"> <div class="row"> <div class="col-lg-4 col-6 img-thumbnail"><img src="https://d2lm6fxwu08ot6.cloudfront.net/img-thumbs/960w/04LDEYRW59.jpg" alt=""></ ...