A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 陈君 金牌黑马   /  2014-8-18 17:38  /  802 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

Form2构造函数中接收一个string类型参数,即Form1中选中行的文本,将Form2的TextBox控件的Text设置为该string,即完成了Form1向Form2的传值
当Form2的AcceptChange按钮按下,需要修改Form1中ListBox中相应列的值,因此可以考虑同时将Form1中的ListBox控件当参数也传入Form2,所有修改工作都在Form2中完成,根据这个思路,Form2代码如下:

  1. publicpartial class Form2 : Form
  2. {
  3. private string text;
  4. private ListBox lb;
  5. private int index;

  6. //构造函数接收三个参数:选中行文本,ListBox控件,选中行索引
  7. public Form2(string text,ListBox lb,int index)
  8. {
  9. this.text = text;
  10. this.lb = lb;
  11. this.index = index;
  12. InitializeComponent();
  13. this.textBox1.Text = text;
  14. }

  15. private void btnChange_Click(object sender, EventArgs e)
  16. {
  17. string text = this.textBox1.Text;
  18. this.lb.Items.RemoveAt(index);
  19. this.lb.Items.Insert(index, text);
  20. this.Close();
  21. }
  22. }
复制代码

Form1中new窗体2时这么写:

  1. public partial class Form1 :Form
  2. {
  3. int index = 0;
  4. string text = null;
  5. public Form1()
  6. {
  7. InitializeComponent();
  8. }

  9. private void listBox1_SelectedIndexChanged(object sender, EventArgse)
  10. {
  11. if (this.listBox1.SelectedItem != null)
  12. {
  13. text = this.listBox1.SelectedItem.ToString();
  14. index = this.listBox1.SelectedIndex;

  15. //构造Form2同时传递参数
  16. Form2 form2 = new Form2(text, listBox1, index);
  17. form2.ShowDialog();
  18. }
  19. }
复制代码

OK,这样做的好处是直观,需要什么就传什么,缺点也是显而易见的,如果窗体1中需要修改的是一百个控件,难道构造的时候还传100个参数进去?况且如果其他窗体仍然需要弹Form2,那Form2就废了,只能供窗体1使用,除非写重载的构造函数,不利于代码的复用

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马