简体   繁体   English

动态创建控件

[英]Creating controls dynamically

I am doing a project for class but can't figure out this small pease that has being keeping me up nights. 我正在做一个课堂上的项目,但无法弄清楚这个让我夜不能寐的小事。 I am creating a page dynamically and it makes a panel for each entry in a database. 我正在动态创建一个页面,它为数据库中的每个条目创建一个面板。 Now the problem is i use one button for all the buttons on each panel. 现在的问题是我使用一个按钮来显示每个面板上的所有按钮。 I need to be able to know what button was pressed so i can send the CarID in a session to another Page. 我需要能够知道按下了什么按钮,这样我就可以将会话中的CarID发送到另一个页面。

namespace SportBucks
{
public partial class Auction : System.Web.UI.Page
{
    string GCarID = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        bool bWinnerID = false;
        bool bWiningBet = false;

        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        if ((string)Session["LoggedIn"] == null)
        {
            Response.Redirect("Default.aspx");
        }
        else
        {
            Service s = new Service();
            int Total = s.CarsCount();
            for (int loop = Total; loop > 0; loop--)
            {
                Panel Panel1 = new Panel();
                Panel1.ID = "pnl" + loop.ToString();
                Panel1.Style["position"] = "absolute";
                Panel1.Style["left"] = "155px";
                Panel1.Style["top"] = "250px";
                Panel1.Style["Height"] = "200px";
                Panel1.Style["Width"] = "1000px";
                Panel1.BackColor = System.Drawing.Color.Black;

                if (loop >= 2)
                {
                    int Top = (250 * (loop - 1));
                    Panel1.Style["top"] = (250 + Top + 20).ToString() + "px";
                }
                form1.Controls.Add(Panel1);
                string Details = s.LoadCars(loop);
                if (Details != null)
                {
                    string CarID = Details.Substring(0, Details.IndexOf("|"));
                    Details = Details.Replace(CarID + "|", "");
                    string Man = Details.Substring(0, Details.IndexOf("|"));
                    Details = Details.Replace(Man + "|", "");
                    string Class = Details.Substring(0, Details.IndexOf("|"));
                    Details = Details.Replace(Class + "|", "");
                    string Type = Details.Substring(0, Details.IndexOf("|"));
                    Details = Details.Replace(Type + "|", "");
                    string Description = Details.Substring(0, Details.IndexOf("|"));
                    Details = Details.Replace(Description + "|", "");
                    string Reserve = Details.Substring(0, Details.IndexOf("|"));
                    Details = Details.Replace(Reserve + "|", "");
                    string Starting = Details.Substring(0, Details.IndexOf("|"));
                    Details = Details.Replace(Starting + "|", "");
                    string Begun = Details.Substring(0, Details.IndexOf("|"));
                    Details = Details.Replace(Begun + "|", "");
                    Begun = Begun.Substring(0, Begun.IndexOf(" "));
                    string End = Details.Substring(0, Details.IndexOf("|"));
                    Details = Details.Replace(End + "|", "");
                    End = End.Substring(0, End.IndexOf(" "));
                    string WinnerID = "";
                    string WinningBet = "";
                    if (Details.Substring(0, 1) == "|")
                    {
                        bWinnerID = false;
                        Details = Details.Substring(1);
                    }
                    else
                    {
                        WinnerID = Details.Substring(0, Details.IndexOf("|"));
                        Details = Details.Replace(WinnerID + "|", "");
                        bWinnerID = true;
                    }

                    if (Details.Substring(0, 1) == "|")
                    {
                        Details = Details.Substring(1);
                        bWiningBet = false;
                    }
                    else
                    {
                        WinningBet = Details.Substring(0, Details.IndexOf("|"));
                        Details = Details.Replace(WinningBet + "|", "");
                        bWiningBet = true;
                    }

                    string PicUrl = Details.Substring(0, Details.IndexOf("|"));
                    int Counter = PicUrl.Split(';').Length - 1;
                    if (Counter >= 1)
                    {
                        Image image1 = new Image();
                        image1.ID = "img" + CarID;
                        image1.ImageAlign = ImageAlign.AbsMiddle;
                        image1.Visible = true;
                        string Pic1 = PicUrl.Substring(0, PicUrl.IndexOf(";"));
                        image1.ImageUrl = Pic1;
                        image1.Style["Left"] = "10px";
                        image1.Style["position"] = "absolute";
                        image1.Style["top"] = "10px";
                        image1.Height = 180;
                        image1.Width = 230;
                        Panel1.Controls.Add(image1);

                    }
                    Label label1 = new Label();
                    label1.ID = "lblDescription" + CarID;
                    label1.Text = Description;
                    label1.ForeColor = System.Drawing.Color.Lime;
                    label1.BorderStyle = BorderStyle.Groove;
                    label1.BorderColor = System.Drawing.Color.Violet;
                    label1.Style["Left"] = "500px";
                    label1.Style["position"] = "absolute";
                    label1.Style["top"] = "30px";
                    Panel1.Controls.Add(label1);

                    Label label2 = new Label();
                    label2.ID = "lblBegun" + CarID;
                    label2.Text = "Auction Start: " + Begun;
                    label2.ForeColor = System.Drawing.Color.Lime;
                    label2.Style["Left"] = "270px";
                    label2.Style["position"] = "absolute";
                    label2.Style["top"] = "30px";
                    Panel1.Controls.Add(label2);

                    Label label3 = new Label();
                    label3.ID = "lblEnd" + CarID;
                    label3.Text = "Auction End: " + End;
                    label3.ForeColor = System.Drawing.Color.Lime;
                    label3.Style["Left"] = "270px";
                    label3.Style["position"] = "absolute";
                    label3.Style["top"] = "50px";
                    Panel1.Controls.Add(label3);

                    Label label4 = new Label();
                    label4.ID = "lblReserve" + CarID;
                    label4.Text = "Reserve: " + Reserve;
                    label4.ForeColor = System.Drawing.Color.Lime;
                    label4.Style["Left"] = "270px";
                    label4.Style["position"] = "absolute";
                    label4.Style["top"] = "70px";
                    Panel1.Controls.Add(label4);

                    Label label5 = new Label();
                    label5.ID = "lblMan" + CarID;
                    label5.Text = "Manufacturer: " + Man;
                    label5.ForeColor = System.Drawing.Color.Lime;
                    label5.Style["Left"] = "270px";
                    label5.Style["position"] = "absolute";
                    label5.Style["top"] = "90px";
                    Panel1.Controls.Add(label5);

                    Label label6 = new Label();
                    label6.ID = "lblClass" + CarID;
                    label6.Text = "Class: " + Class;
                    label6.ForeColor = System.Drawing.Color.Lime;
                    label6.Style["Left"] = "270px";
                    label6.Style["position"] = "absolute";
                    label6.Style["top"] = "110px";
                    Panel1.Controls.Add(label6);

                    Label label7 = new Label();
                    label7.ID = "lblType" + CarID;
                    label7.Text = "Type: " + Type;
                    label7.ForeColor = System.Drawing.Color.Lime;
                    label7.Style["Left"] = "270px";
                    label7.Style["position"] = "absolute";
                    label7.Style["top"] = "130px";
                    Panel1.Controls.Add(label7);

                    if (bWinnerID == true)
                    {
                        Label label8 = new Label();
                        label8.ID = "lblWinnerID" + CarID;
                        label8.Text = "WinnerID: " + WinnerID;
                        label8.ForeColor = System.Drawing.Color.Lime;
                        label8.Style["Left"] = "270px";
                        label8.Style["position"] = "absolute";
                        label8.Style["top"] = "130px";
                        Panel1.Controls.Add(label8);
                    }
                    if (bWiningBet == true)
                    {
                        Label label9 = new Label();
                        label9.ID = "lblWinningBet" + CarID;
                        label9.Text = "WinningBet R: " + WinningBet;
                        label9.ForeColor = System.Drawing.Color.Lime;
                        label9.Style["Left"] = "270px";
                        label9.Style["position"] = "absolute";
                        label9.Style["top"] = "130px";
                        Panel1.Controls.Add(label9);
                    }

                    /*int View = s.TimesView(CarID);
                    Label label10 = new Label();
                    label10.ID = "lblView" + CarID;
                    label10.Text = "Times View: " + View;
                    label10.ForeColor = System.Drawing.Color.Lime;
                    label10.Style["Left"] = "1000px";
                    label10.Style["position"] = "absolute";
                    label10.Style["top"] = "130px";
                    Panel1.Controls.Add(label10);*/

                    Button btnView = new Button();
                    btnView.ID = CarID;
                    btnView.Text = "View Car";
                    btnView.ForeColor = System.Drawing.Color.DeepSkyBlue;
                    btnView.BackColor = System.Drawing.Color.Gray;
                    btnView.BorderColor = System.Drawing.Color.Violet;
                    btnView.Style["top"] = "110px";
                    btnView.Style["left"] = "800px";
                    btnView.Style["Height"] = "20px";
                    btnView.Style["position"] = "absolute";
                    btnView.BorderStyle = BorderStyle.Outset;
                    btnView.Click += new EventHandler(this.btnView_Click);
                    GCarID = CarID;
                    Panel1.Controls.Add(btnView);
                }
            }
        }
    }

            void btnView_Click(object sender, EventArgs e)
            {
                Session["CarID"] = GCarID;
                Response.Redirect("View.aspx");
            }

}}

Try add a custom html attribute. 尝试添加自定义html属性。

//code behind: //代码背后:

Button btnView = new Button();
btnView.ID = CarID;
//here
btnView.Attributes.Add("GCarID", CarID);
btnView.Text = "View Car";
btnView.ForeColor = System.Drawing.Color.DeepSkyBlue;
btnView.BackColor = System.Drawing.Color.Gray;
btnView.BorderColor = System.Drawing.Color.Violet;
btnView.Style["top"] = "110px";
btnView.Style["left"] = "800px";
btnView.Style["Height"] = "20px";
btnView.Style["position"] = "absolute";
btnView.BorderStyle = BorderStyle.Outset;
btnView.Click += new EventHandler(this.btnView_Click);

//click
void btnView_Click(object sender, EventArgs e)
{
    Session["CarID"] = ((Button)sender).Attributes["GCarID"];
    Response.Redirect("View.aspx");
}

You need to understand the ASP.NET Life Cycle . 您需要了解ASP.NET生命周期 Your dynamic controls need to be created in the Page_Init() stage, not the Page_Load(). 您需要在Page_Init()阶段创建动态控件,而不是Page_Load()。

What is happening is you are creating your controls in the Page_Load and when you click on a button and a post back occurs, your dynamic controls are being destroyed. 发生的事情是你在Page_Load中创建控件,当你点击按钮并发回帖子时,你的动态控件就被破坏了。 The viewstate for controls is created after the Page_Init, but before the Page_Load. 控件的视图状态是在Page_Init之后但在Page_Load之前创建的。 Therefore, your control's that you create dynamically are not keeping their values (such as the ID). 因此,您动态创建的控件不会保留其值(例如ID)。

Check out this page and this page for a basic understanding of what I am talking about. 查看此页面此页面,以便基本了解我所说的内容。

What's the issue? 有什么问题? In your event handler btnView_Click(object sender, EventArgs e), the sender would be the button which got clicked. 在您的事件处理程序btnView_Click(对象发送者,EventArgs e)中,发件人将是被点击的按钮。 Just cast sender to Control or Button => (sender as Control) or (sender as Button) and retrieve the carID from the ID property.. (which you set in page load) - btnView.ID = CarID; 只需将发件人转换为Control或Button =>(发件人作为控件)或(发件人作为按钮)并从ID属性中检索carID ..(您在页面加载中设置) - btnView.ID = CarID;

This is of course assuming your page viewstate is working fine :) - which can be tricky with dynamically added controls in asp.net 这当然是假设您的页面视图状态正常工作:) - 这在asp.net中动态添加控件可能会很棘手

You want to use Button's Command event with CommandArgument instead of Click event. 您希望将Button的Command事件与CommandArgument一起使用,而不是使用Click事件。

CommandArgument is meant for that kind of storing arguments, and retrieves it back on past back. CommandArgument适用于那种存储参数,并在过去的背面检索它。

Button btnView = new Button();
btnView.ID = CarID;
btnView.Text = "View Car";
btnView.ForeColor = System.Drawing.Color.DeepSkyBlue;
btnView.BackColor = System.Drawing.Color.Gray;
btnView.BorderColor = System.Drawing.Color.Violet;
btnView.Style["top"] = "110px";
btnView.Style["left"] = "800px";
btnView.Style["Height"] = "20px";
btnView.Style["position"] = "absolute";
btnView.BorderStyle = BorderStyle.Outset;
btnView.Command += btnView_Command; // Note: Command event is used instead of Click.
btnView.CommandArgument = CarID; // Note: CarID is stored in CommandArgument.
Panel1.Controls.Add(btnView);

void btnView_Command(object sender, CommandEventArgs e)
{
    string carID = e.CommandArgument.ToString();
    Session["CarID"] = carID;
    Response.Redirect("View.aspx");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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