简体   繁体   中英

Add button to webpage via code behind in asp.net and delete dynamic db entrys

Hi im wondering if its possible to add a asp button to the code below, the code below adds an image and text from my database to 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 is the strange thing tho, if I do manage to add a button similar to the way I have added an image, how would I call that button, for example:

I want to call this button "delete" and add code to delete the text in my database related to that div, but if there is multiple divs(there all named the same div id=test) with text and they all have the same asp button how would I be able to tell the button to only delete the current text(in the db) for the current div??

My database stores the information like so:

在此输入图像描述

Im thinking I would have to use idwallposting but not sure how?

Also to give a visual representation of how it looks it may help aid in the understanding:

在此输入图像描述

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>

Why not give each div a unique ID like div.ID = "test" + idWallPostings; ?

It is not a good idea to have non-unique IDs for any element.

Regarding your main problem, why not use one of the templated data controls like Repeater or ListView and add a Command handler. Then in the template add the button with a command argument for the current data item's data key.

see: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.itemcommand.aspx

You can see how the the button is used to carry additional information in its click event:

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

and how it is retrieved and used (it is accessed using e.CommandArgument):

  protected void EmployeesListView_OnItemCommand(object sender, ListViewCommandEventArgs e)
  {
    if (String.Equals(e.CommandName, "AddToList"))
    {
      // Verify that the employee ID is not already in the list. If not, add the
      // employee to the list.
      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);
      }
    }
  }

For deletion from database with C# in Visual Studio 2008 ASP.net write the following code by double-clicking on 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 is deleted";
        cmd.ExecuteNonQuery();
        conn.Close();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM