【问题标题】:how to assign values to textbox in another method which was dynamically created in c sharp如何在另一种在 c sharp 中动态创建的方法中为文本框赋值
【发布时间】:2013-12-27 19:43:18
【问题描述】:

如何在 c sharp 中动态创建的开始暂停按钮方法中为文本框赋值

 public void btn_addtimer_Click(object sender, EventArgs e)
    {
        var panel1 = new Panel() 
            { 
                Size = new Size(500, 180), 
                Location = new Point(10, i), 
                BorderStyle = BorderStyle.FixedSingle 
            };
        TextBox textseconds = new TextBox();
        textseconds.Name = "txtseconds";
        textseconds.Location = new Point(350, 50);
        textseconds.KeyPress += textseconds_KeyPress;
        panel1.Controls.Add(textseconds);


        Button startpause = new Button();
        startpause.Name = "btnstartpause";
        startpause.Text = "Start";
        startpause.Location = new Point(350, 80);
        startpause.Click += btnstartpause_Click;
        panel1.Controls.Add(startpause);

    }

【问题讨论】:

  • 您正在为该代码中已存在的Button 的多个属性分配值。什么意思?
  • 为什么要动态创建面板和按钮?您可以添加面板和按钮并隐藏按钮:startpause.Visible =false;然后在需要时显示它。您可以分配当时需要的任何值。
  • @user3132774 你能发布你的btnstartpause 方法吗?
  • @user3132774 检查您需要将id 分配给您的文本框的答案\

标签: c# winforms


【解决方案1】:

将 FindControl 与强制转换一起使用:

((TextBox)FindControl("textseconds")).Text = "Some text here";

【讨论】:

  • 如何在 btnstartpause 方法中将文本分配给 textseconds.text
  • 它显示 FindControl 在当前比赛中不存在
  • @rkawano +1 顺便拿了你的代码!唯一缺少的是分配 id ,FindControl 方法在当前命名容器中搜索具有指定 id 参数的服务器控件。
【解决方案2】:

为他们分配 ID

        textseconds.Id ="txtbxScnds";

然后使用

((TextBox)FindControl("textseconds")).Text = "Some text here";

FindControl 方法在当前命名容器中搜索具有指定id 参数的服务器控件。

但是,您需要在每次回发时重新创建动态控件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-07
    • 2012-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多