Implement a button onto a webpage using code behind in ASP.NET to remove dynamically generated database entries

Hello, I am curious if it is feasible to include an asp button in the code provided below. This code fetches an image and text from my database and inserts them into a dynamic div on my ASP page:

using System.Data.Odbc;
using System.IO;

public partial class UserProfileWall : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        string theUserId = Session["UserID"].ToString();
        PopulateWallPosts(theUserId);
    }
    private void PopulateWallPosts(string userId)
    {

        using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;"))
        {
            cn.Open();
            using (OdbcCommand cmd = new OdbcCommand("SELECT wp.WallPostings, p.PicturePath FROM WallPosting wp LEFT JOIN User u ON u.UserID = wp.UserID LEFT JOIN Pictures p ON p.UserID = u.UserID WHERE wp.UserID=" + userId + " ORDER BY idWallPosting DESC", cn))
            {
                //("SELECT wp.WallPostings, p.PicturePath FROM WallPosting wp LEFT JOIN [User] u ON u.UserID = wp.UserID LEFT JOIN Pictures p ON p.UserID = u.UserID WHERE UserID=" + userId + " ORDER BY idWallPosting DESC", cn))
                using (OdbcDataReader reader = cmd.ExecuteReader())
                {
                    test1.Controls.Clear();

                    while (reader.Read())
                    {
                        System.Web.UI.HtmlControls.HtmlGenericControl div = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
                        div.Attributes["class"] = "test";
                //div.Style["float"] = "left";

                        div.ID = "test";
                        Image img = new Image();
                        img.ImageUrl = String.Format("{0}", reader.GetString(1));
                        // this line needs to be represented in sql syntax
                        //img.ImageUrl = "~/userdata/2/uploadedimage/batman-for-facebook.jpg";
                        img.AlternateText = "Test image";

                        div.Controls.Add(img);
                        div.Controls.Add(ParseControl(String.Format("&nbsp&nbsp "+"{0}", reader.GetString(0))));
                        div.Style["clear"] = "both";
                        test1.Controls.Add(div);

                    }
                }
            }
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string theUserId = Session["UserID"].ToString();
        using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;"))
        {
            cn.Open();
            using (OdbcCommand cmd = new OdbcCommand("INSERT INTO WallPosting (UserID, Wallpostings) VALUES (" + theUserId + ", '" + TextBox1.Text + "')", cn))
            {
                cmd.ExecuteNonQuery();
            }
        }
        PopulateWallPosts(theUserId);
    }
}

Here's what puzzles me - If I successfully add a button similar to how I added an image, how can I reference that button? For example:

I intend to name this button "delete" and implement code to delete the text in my database associated with that particular div. But if there are multiple divs (all named the same div id=test) containing text and each has the same asp button, how do I ensure the button only deletes the current text (in the db) for the current div?

The information stored in my database looks like this:

I believe I might need to utilize idwallposting but I'm unsure about the specifics.

In order to visually illustrate how it appears, consider the following:

My CSS and ASP:

div#test1 {
}
div .test {
  width:90%; 
  z-index:1; 
  padding:27.5px; 
  border-top: thin solid #736F6E;
  border-bottom: thin solid #736F6E;
  color:#ffffff;
  margin:0 auto;
  white-space: pre;
  white-space: pre-wrap;
  white-space: pre-line;
  word-wrap: break-word;
}

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.js" type="text/javascript"></script>
<p>
    <asp:TextBox ID="TextBox1" name="TextBox1" runat="server" Rows="3" 
        Height="47px" Width="638px"></asp:TextBox>
</p>
<p>
     <asp:Button ID="Button1" runat="server" Text="Post Message" Width="98px" 
        onclick="Button1_Click" />
    </p>
<p>
</p>
    <style type="text/css">
    img {border-width:0px; width:100px; height:100px;}
</style>
    <div id="test1" runat="server" />


    </div>


</asp:Content>

Answer №1

Have you considered assigning a unique ID to each div element, such as div.ID = "test" + idWallPostings?

It's crucial to ensure that all IDs are unique for every element.

Regarding your primary issue, have you thought about using templated data controls like Repeater or ListView and adding a Command handler? You can then include a button in the template with a command argument specific to the current data item's data key.

For more information, check out: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.itemcommand.aspx

You'll notice how the button carries additional information in its click event:

<asp:LinkButton runat="server" 
                ID="SelectEmployeeButton" 
                Text="Add To List" 
                CommandName="AddToList" 
                CommandArgument='<%#Eval("LastName") + ", " + Eval("FirstName") %>' />

And here's how you retrieve and use this information (accessed through e.CommandArgument):

  protected void EmployeesListView_OnItemCommand(object sender, ListViewCommandEventArgs e)
  {
    if (String.Equals(e.CommandName, "AddToList"))
    {
      // Check if employee ID is not already in the list. If not, add the employee.
      ListViewDataItem dataItem = (ListViewDataItem)e.Item;
      string employeeID = 
        EmployeesListView.DataKeys[dataItem.DisplayIndex].Value.ToString();

      if (SelectedEmployeesListBox.Items.FindByValue(employeeID) == null)
      {
        ListItem item = new ListItem(e.CommandArgument.ToString(), employeeID);
        SelectedEmployeesListBox.Items.Add(item);
      }
    }
  }

Answer №2

To delete records from a database using C# in Visual Studio 2008 ASP.net, simply follow these steps and double-click on the button:

protected void btndel_Click(object sender, EventArgs e)
    {

        SqlConnection conn;
        SqlCommand cmd;
        conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\THEGIRL\\Documents\\Visual Studio 2008\\WebSites\\WebSite72\\App_Data\\Database.mdf';Integrated Security=True;User Instance=True");
        conn.Open();
        cmd = new SqlCommand("Delete from logintable where username='"+txtdeluname.Text+"'",conn);
        lbldel.Text = "Record has been deleted";
        cmd.ExecuteNonQuery();
        conn.Close();
    }

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

What could be causing the issue with my Bootstrap Scrollspy?

I'm sure you're familiar with CodePen questions. Here's mine: https://codepen.io/fender90/pen/KqVLba HTML <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="https://maxcdn ...

Display each set of multiple results in an HTML table

I am attempting to retrieve data from 2 SQL queries and display them in an HTML table. However, I am experiencing issues with getting the correct results. Can someone please assist me with resolving this problem? The code provided below shows that the sec ...

What steps can be taken to ensure the function is run every 5 seconds?

I have a task where I need to set up the amurFunc() function to run every 5 seconds. The function acts as a listener that detects when the user clicks on a specific div element. They should be able to click it once every 5 seconds. Can you help me troubles ...

HTML/CSS: Issue with image grid layout where images of different heights are not wrapping correctly

I have a Wordpress-based web project in progress at the following link: The current setup of the post thumbnails grid on the website was done with the assumption that all thumbnails will be the same height. However, I am looking to modify it so that the t ...

assigning a label to a DropDownList

When attempting to place a label in front of a DropdownList, the dropdownlist appears on the next line. I have tried various suggestions from different sources but have not been able to find a solution. Here is the simple code I am currently using: Group ...

What is the most effective ASP.net Authentication/Membership Model?

Starting a new ASP.net Web Forms application and decided to use the ASP.net Identity System as the default option. However, I quickly realized that it lacked some features compared to the older ASP.net Membership service. The lack of documentation on how t ...

Adjusting the contenteditable feature to place the caret on a specific child node

I am experiencing some challenges when attempting to position the cursor after an <i> tag within a contenteditable element. Currently, this is what I have: <p contenteditable="true"><i>H</i><i>e</i><i>l</i> ...

Is it possible for jQuery to execute in a sequential manner?

Below is the code I am working with: https://jsfiddle.net/c4zquo60/1/ CSS: #bg { background-repeat: no-repeat; position: absolute; top:0; bottom:0; left:0; right:0; width:100wh; height:100vh; z-index: -1; opacity: ...

Forcing an iframe in an ASP.NET web application to refresh and reload

Although I have experience in .NET Core development, ASP.NET Web Apps are new territory for me. Within my Index.cshtml, there is an iframe with the following attributes: <iframe height="800" width="1300" loa ...

The entire title serves as a hyperlink, not just the text portion

Apologies if I'm making mistakes, I'm just starting out with coding and navigating this website. So here's the deal: I am trying to add advertisements to my website on the left and right sides of the centered "Logo" at the top. The issue i ...

Tips for adding multiple audio tracks to a video using JavaScript

I am currently working on a video player that can play MP4 videos without audio files embedded in them. In addition to the video, I have two separate audio files available in English and Italian languages. To implement language selection functionality, ...

Execute operation in MySQL

I have developed 3 different procedures, and the third one calls the first two: calculate pi function DELIMITER $$ DROP PROCEDURE IF EXISTS calculate_pi$$ CREATE PROCEDURE calculate_pi() BEGIN DECLARE pi_value FLOAT; SET pi_value = 3.14; SELECT pi_value; ...

Can the asynchronous function be further optimized?

Here is a function that I have: public async Task<string> EagerLoadAllAsync<T>(params Expression<Func<T, object>>[] includeProperties) where T : class { var entities = await _repository.EagerLoadAllAsync(includeProperties); ...

Adding a data entry to a detailsview with the insert command

How can I prepopulate a textbox in a detailsview during the insert command? I believe this code behind should work: Dim txtBox As TextBox = FormView1.FindControl("txtbox") txtbox.Text = "Whatever I want" Is this correct? What do I need on the aspx side ...

Changing the background color of the canvas using Javascript

I want to create a rect on a canvas with a slightly transparent background, but I don't want the drawn rect to have any background. Here is an example of what I'm looking for: https://i.stack.imgur.com/axtcE.png The code I am using is as follo ...

Is there a way to include clickable links within my dropdown menu?

I'm having an issue trying to create a dropdown menu with links on my website, but it doesn't seem to be working. <!doctype html> <html> <head> <style> a.mainhrf ul.mainul { display: none; } a. ...

Unable to change background image using jQuery

Snippet: const imageUrl = 'img/star.png'; $("#venueId-"+nodeId).css('background','url("'+imageUrl+'") no-repeat top right'); This piece of code is the start of a function that triggers upon clicking. The goal is to ...

Troubleshooting the failure of enabling AWS X-Ray for MySQL JPA Repository in Spring

Currently, I am in the process of implementing AWS X-Ray instrumentation for Mysql calls within my Spring application. The instrumentation for HTTP and S3 is functioning correctly. To achieve this, I have configured the property: spring.datasource.jdbc-in ...

Issues with Bootstrap sidebar and footer functionality

I need to implement a consistent footer on multiple web pages created with jQuery and bootstrap 3. Following the example provided by Bootstrap, I have written the script below to add the footer: // Default $( document ).ready(function() { $(' ...

PHP: When an Array Key is Not Defined

https://i.sstatic.net/k2d1Z.png This is the result I am trying to organize and display my data in tables based on the date. I have stored the data from the database in an array for this purpose. However, I am encountering an error warning stating 'un ...