简体   繁体   中英

How do I dynamically add a label and button to a groupbox?

I'm building a program that will insert/update/delete entries in my database.

What's next on the to-do list is to dynamically populate a groupbox with labels and buttons depending on how many entries it finds in the database, but I'm not sure on how to do this.

My query looks like "SELECT id, image FROM images WHERE slider = 1";

Where all entries with slider = 1 in the database display the image in the image-slider on the website and slider = 0 does not display it.

So in the program i would like to display the label of the image and a button to remove the image from the slider in the groupbox i set in design view. (when you click the delete button it will update the database and set the column slider to 0 for that image based on the id).

EG:

Groupbox

image1 <delete> <--button
image2 <delete> <--button

EDIT

I forgot to mention that the population should occur when i click on the toolstrip in the top menu

EG:

private void imagesToolStripMenuItem_Click(object sender, EventArgs e)
{
    Pnl_Media.Visible = true;

    Lbl_Welcome_admin.Visible = false;
    Lbl_Text_Admin.Visible = false;

    //Populate the groupbox here
}

/EDIT

So my question is: How can i populate my existing empty groupbox with the code block above?

With thanks

Jim

If I understand you correctly you want to create labels and buttons in code, and have a OnClick attached to the buttons?

You can do that like this.

If this is not what you want than please clarify what you mean.

You can create objects like labels and buttons like this:

        Label lbl = new Label();
        lbl.Name = "label1";
        lbl.Parent = groupBox1;
        lbl.Text = "hello world";
        lbl.SetBounds(10, 10, 75, 21);

        Button btn = new Button();
        btn.Name = "button1";
        btn.Parent = groupBox1;
        btn.Text = "delete something";
        btn.SetBounds(10, 50, 75, 21);
        btn.Click += btn_Click;

    void btn_Click(object sender, EventArgs e)
    {
        if (sender is Button)
        {
            MessageBox.Show("clicked on " + ((Button)sender).Name);
        }
    }

 <script type="text/javascript" language="javascript"> function removeImage(id) { PageMethods.RemoveImage(id, onSucess, onError); } function onSucess(result) { alert(result); document.getElementById("btnClick").click(); } function onError(result) { alert('Something wrong.'); } </script> 
 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DynamicData_JIM._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type="text/javascript" language="javascript"> function removeImage(id) { PageMethods.RemoveImage(id, onSucess, onError); } function onSucess(result) { alert(result); document.getElementById("btnClick").click(); } function onError(result) { alert('Something wrong.'); } </script> </head> <body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager> <div> <asp:Button ID="btnClick" Text="Click" runat="server" OnClick="btnClick_Click" /> <asp:Panel ID="pnldynamic" runat="server"> </asp:Panel> </div> </form> </body> </html> 

    protected void btnClick_Click(object sender, EventArgs e)
    {
        try
        {
            using (DBM.SqlCommandEx sqlCmd = new DBM.SqlCommandEx(String.Format("SELECT  [id],[image] FROM images WHERE slider = 1", "", "")))
            {
                System.Data.DataTable dt = new System.Data.DataTable();
                dt = sqlCmd.GetDataTable();


                Int32 icount = 0;
                pnldynamic.Controls.Clear();
                pnldynamic.Controls.Add(new LiteralControl("<table>"));
                foreach (System.Data.DataRow dr in dt.Rows)
                {

                    String LabelId = "lbl" + icount.ToString();
                    String buttonid = dr["id"].ToString();

                    pnldynamic.Controls.Add(new LiteralControl("<tr><td>"));

                    pnldynamic.Controls.Add(new LiteralControl("<span>" + dr["image"].ToString() + "</span>"));
                    pnldynamic.Controls.Add(new LiteralControl("</td><td>"));

                    pnldynamic.Controls.Add(new LiteralControl("<input type='button' id=" + buttonid + " value='Remove' onclick='removeImage(" + dr["id"].ToString() + ");' />"));


                    pnldynamic.Controls.Add(new LiteralControl("</td></tr>"));


                    icount++;
                }
                pnldynamic.Controls.Add(new LiteralControl("</table>"));

            }
        }
        catch (Exception ex)
        {
            string err = ex.ToString();
        }


    }


    [WebMethod]
    public static string RemoveImage(string id)
    {
        String msg = "Success";
        Int32 iresult = 0;
        try
        {
            iresult = DBM.ExecuteNonQuery("UPDATE   images SET  slider = 0 WHERE id = " + id + "");
        }
        catch (Exception ex)
        {
            string err = ex.ToString();
        }
        return msg;
    }

}

DBM.cs

private static string GetConnectionString()
{
    return ConfigurationManager.ConnectionStrings["StackOverflow"].ConnectionString;
}

public static string CleanSQL(string data)
{
    return data.Replace("'", "''");
}

public static int ExecuteNonQuery(string SQL)
{
    using (SqlConnection conn = new SqlConnection(GetConnectionString()))
    {
        conn.Open();

        SqlCommand cmd = new SqlCommand(SQL, conn);
        int result = cmd.ExecuteNonQuery();

        conn.Close();
        return result;
    }
}
public static object ExecuteScalar(string SQL)
{
    using (SqlConnection conn = new SqlConnection(GetConnectionString()))
    {
        conn.Open();

        SqlCommand cmd = new SqlCommand(SQL, conn);
        object result = cmd.ExecuteScalar();

        conn.Close();
        return result;
    }
}

public class SqlCommandEx : IDisposable
{
    private SqlConnection conn;
    public SqlCommand CommandObject;

    //public static System.Collections.Stack inuse = new System.Collections.Stack();

    public SqlCommandEx(string SQL)
    {
        conn = new SqlConnection(GetConnectionString());
        conn.Open();

        CommandObject = new SqlCommand(SQL, conn);
        //inuse.Push(DateTime.Now);
    }

    public DataTable GetDataTable()
    {
        SqlDataAdapter da = new SqlDataAdapter(CommandObject);
        DataTable dt = new DataTable();
        da.Fill(dt);
        return dt;
    }

    public void AddWithValue(string parameter, object value)
    {
        CommandObject.Parameters.AddWithValue(parameter, value);
    }

    public void Dispose()
    {
        //inuse.Pop();
        conn.Close();
    }
}

public static DataTable GetDataTable(string SQL)
{
    using (SqlConnection conn = new SqlConnection(GetConnectionString()))
    {
        conn.Open();

        SqlDataAdapter da = new SqlDataAdapter(SQL, conn);
        DataTable result = new DataTable();
        da.Fill(result);

        conn.Close();
        return result;
    }
}

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