1、动态添加选项卡,并加载DataGridVIew,绑定数据
private void MainForm_Load(object sender, EventArgs e) { int newsId = 0; dtType = News_Release.News_BLL.BLL.Cmb_Type(newsId); for (int i = 0; i < dtType.Rows.Count; i++) { TabPage Page = new TabPage(); Page.Name = dtType.Rows[i]["Classification_ID"].ToString(); Page.Text = dtType.Rows[i]["Name"].ToString(); this.tcHomePage.Controls.Add(Page); if(i==0) { Page.Controls.Add(dataGridView1); this.dataGridView1.Dock = DockStyle.Fill; } } this.dataGridView1.AllowUserToAddRows = false; this.dataGridView1.ReadOnly = true; this.dataGridView1.DataSource = Login.BLL_Login.MainForm.selectedNews(Convert.ToInt32(dtType.Rows[0]["Classification_ID"].ToString())); } private void tcHomePage_SelectedIndexChanged(object sender, EventArgs e) { int newsClassification = Convert.ToInt32(tcHomePage.SelectedTab.Name); //string typeName = tcHomePage.SelectedTab.Text; tcHomePage.SelectedTab.Controls.Add(dataGridView1); this.dataGridView1.Dock = DockStyle.Fill; this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; this.dataGridView1.AllowUserToAddRows = false; this.dataGridView1.DataSource = Login.BLL_Login.MainForm.selectedNews(newsClassification); }
2、新建一个WinForm程序,拖一个TabControl(在tabPages属性里面将默认的两个TabPage删除)和三个Button(增加、删除、修改)
- public partial class Form1 : Form
- {
- private int index = 0;
- public Form1()
- {
- InitializeComponent();
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- //this.tabControl1.SelectedIndex = 1;
- }
- private void btnAdd_Click(object sender, EventArgs e)
- {
- TabPage Page = new TabPage();
- Page.Name = "Page" + index.ToString();
- Page.Text = "tabPage" + index.ToString();
- Page.TabIndex = index;
- this.tabControl1.Controls.Add(Page);
- #region 三种设置某个选项卡为当前选项卡的方法
- //this.tabControl1.SelectedIndex = index;
- this.tabControl1.SelectedTab = Page;
- //this.tabControl1.SelectTab("Page" + index.ToString());
- #endregion
- index++;
- }
- private void btnRemove_Click(object sender, EventArgs e)
- {
- bool first = true;
- if (index > 0)
- {
- #region 两种删除某个选项卡的方法
- this.tabControl1.Controls.RemoveAt(this.tabControl1.SelectedIndex);
- //this.tabControl1.Controls.Remove(this.tabControl1.TabPages[this.tabControl1.TabPages.Count-1]);
- #endregion
- }
- else
- {
- return;
- }
- #region 用于设置删除最后一个TabPage后,将倒数第二个设置为当前选项卡
- if (first)
- {
- this.tabControl1.SelectedIndex = --index - 1;
- first = false;
- }
- else
- {
- this.tabControl1.SelectedIndex = index--;
- }
- #endregion
- }
- private void btnUpdate_Click(object sender, EventArgs e)
- {
- this.tabControl1.SelectedTab.Text = "xyt";//修改当前选项卡的属性
- //this.tabControl1.SelectedTab.Name = "";
- //this.tabControl1.SelectedTab.Tag = "";
- //this.tabControl1.SelectedTab.Select();
- }
- }