C#在运行时添加带值的按钮

我想在运行时向我的选项卡控件添加一个有值的按钮。 很多教程都展示了创建与数据库连接时的工作方式。 有没有办法可以在不连接数据库的情况下完成?

在此处输入图像描述

在将数据输入文本框和单击保存后,新按钮应出现在另一个表单上的选项卡控件上。

在你保存按钮放:

private void btnSave_Click(object sender, EventArgs e) { x = 4; y = panel1 .Controls.Count * 70; Button newButton = new Button (); newButton.Height = 150; newButton.Width = 60; newButton.Location = new Point(x, y); newButton.Text= "your text"; newButton.Click += new System.EventHandler(Button_Click); tabControl1.TabPages [0].Controls.Add(newButton); } 

您还可以点击创建的新按钮:

 public void Button_Click(object sender, EventArgs e) { Button button = (Button)sender ; MessageBox.Show("Button is pressed "+button .Text ); } 

我提出这样的决定

主要forms:

 namespace stackoverflow { public partial class MainForm : Form { private static Form2 new_form = new Form2(); public MainForm() { InitializeComponent(); new_form.Show(); } void Button1Click(object sender, EventArgs e) { new_form.CreateBtn( richTextBox1.Text ); } } } 

第二种forms:

 namespace stackoverflow { public partial class Form2 : Form { private Button btn = null; public Form2() { InitializeComponent(); } public void CreateBtn( string text ) { if ( btn == null ) { btn= new Button(); btn.Parent = this.tabPage1; } btn.Text = text; this.Refresh(); } } } 
 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Buttons { public partial class Form1 : Form { const int ROWS = 5; const int COLS = 10; public Form1() { InitializeComponent(); this.Load += new System.EventHandler(this.Form1_Load); } public void Form1_Load(object sender, EventArgs e) { new MyButton(ROWS, COLS, this); } } public class MyButton : Button { const int WIDTH = 50; const int HEIGHT = 50; const int SPACE = 5; const int BORDER = 20; public static List> buttons { get; set; } public static List buttonList { get; set; } public Form1 form1; public int row { get; set; } public int col { get; set; } public MyButton() { } public MyButton(int rows, int cols, Form1 form1) { buttons = new List>(); buttonList = new List(); this.form1 = form1; for(int row = 0; row < rows; row++) { List newRow = new List(); buttons.Add(newRow); for (int col = 0; col < cols; col++) { MyButton newButton = new MyButton(); newButton.Height = HEIGHT; newButton.Width = WIDTH; newButton.Top = row * (HEIGHT + SPACE) + BORDER; newButton.Left = col * (WIDTH + SPACE) + BORDER; newButton.row = row; newButton.col = col; newRow.Add(newButton); buttonList.Add(newButton); newButton.Click += new System.EventHandler(Button_Click); form1.Controls.Add(newButton); } } } public void Button_Click(object sender, EventArgs e) { MyButton button = sender as MyButton; MessageBox.Show(string.Format("Pressed Button Row {0} Column {1}", button.row, button.col)); } } }