日期:2014-05-17  浏览次数:21192 次

winform 使用委托方法实现窗体间传值,不刷新dataGridView控件,不解?在线等....
在Form1中有dataGridView控件,在Form1的load事件中,取值,所以在Form1显示的时候,dataGridView中有记录,之后点击一个button,打开Form2,在Form2中,修改数据,使用委托的办法将值传回Form1,现在的问题是:跟踪发现,数据已经返回Form1中,但是就是不刷新dataGridView1控件,不知道原因?

Form2中委托代码
  public delegate void GetDatahandle(List<string>abc); //声明委托
  public partial class importdata : Form
  {
  public event GetDatahandle setString; //定义一个与委托相关的事件
  private void button2_Click(object sender, EventArgs e)
  {
  List<string> rv = new List<string>(); 
  string de="aaa,fff"
  rv.Add(de);
  wage cx1 = new wage();
  setString += new GetDatahandle(cx1.SetViewValue); //订阅一个事件
  if (setString != null)// 触发事件
  setString(rv);
  this.Close();
  }

在Form1的委托处理事件中
 public void SetViewValue(List<string> cx)
  {
  dataGridView1.RowCount = cx.Count + 1;
  char[] es = new char[] { ',' };
  for (int j = 0; j < cx.Count; j++)
  {
  string[] ak = cx[j].Split(es);
  if (ak[0].Equals("0"))
  dataGridView1.Rows[j].Cells[0].Value = " ";
  else
  {
  dataGridView1.Rows[j].Cells[0].Value = ak[0];
  }
  if (ak[1].Equals("0"))
  dataGridView1.Rows[j].Cells[1].Value = " ";
  else
  dataGridView1.Rows[j].Cells[1].Value = ak[1];
  }
  }

另外,在SetViewValue(List<string> cx)中,dataGridView1.Rows.Clear()无效,也不解?


------解决方案--------------------
你订阅事件的代码写的地方不对,正常的方式应该是Form1订阅Form2的事件,你在Form2中订阅自己的事件是没有意义的。
C# code

//Form2中委托代码
public delegate void GetDatahandle(List<string>abc); //声明委托
public partial class importdata : Form
{
  public event GetDatahandle setString; //定义一个与委托相关的事件
  private void button2_Click(object sender, EventArgs e)
  {
     List<string> rv = new List<string>();  
     string de="aaa,fff"
     rv.Add(de);
     wage cx1 = new wage();
     //setString += new GetDatahandle(cx1.SetViewValue); //订阅一个事件
      if (setString != null)// 触发事件
         setString(rv);
     this.Close();
  }
}

//在Form1的委托处理事件中
[color=#FF6600]private void btnShowForm2(object sender, EventArgs e)
{
   Form2 f2 = new Form2();
   f2.setString += new GetDatahandle(this.SetViewValue); 
   f2.ShowDialog();
}[/color]
public void SetViewValue(List<string> cx)
{
  dataGridView1.RowCount = cx.Count + 1;
  char[] es = new char[] { ',' };
  for (int j = 0; j < cx.Count; j++)
  {
     string[] ak = cx[j].Split(es);
     if (ak[0].Equals("0"))
     dataGridView1.Rows[j].Cells[0].Value = " ";
     else
     {
       dataGridView1.Rows[j].Cells[0].Value = ak[0];
     }
     if (ak[1].Equals("0"))
        dataGridView1.Rows[j].Cells[1].Value = " ";
     else
        dataGridView1.Rows[j].Cells[1].Value = ak[1];
   }
   Application.DoEvent();
}

------解决方案--------------------
真乱啊。。。怎么在Form2里自己绑定委托实例啊。不应该是Form1里绑定Form2的事件?

wage cx1 = new wage();
setString += new GetDatahandle(cx1.SetViewValue); //订阅一个事件


wage 是什么?