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

求助c# 类中定义方法不能返回数据
代码如下:
        public void GetExcelData()
        {
            OpenFileDialog _dialog1 = new OpenFileDialog();
            _dialog1.Filter = "Excel文件(*.xls,*.xlsx)|*.xls;*.xlsx";

            if (_dialog1.ShowDialog() == DialogResult.OK)
            {
                string _fileName = _dialog1.FileName.ToString();

                if (_fileName == null || _fileName == "")
                    return;

                OldDB_GetExcelData _GetExcelTable = new OldDB_GetExcelData(_fileName);
                DataTable dt = _GetExcelTable.GetExcelData();

                UserControl1 _myform = new UserControl1();

                _myform.dataGridView1.Columns.Add("aaa", "aaaa");
                _myform.dataGridView1.Rows.Add();
                _myform.dataGridView1.Rows[0].Cells[0].Value = "1111";
                _myform.dataGridView1.Rows[0].Cells[1].Value = "22222";
                _myform.dataGridView1.Update();
                _myform.dataGridView1.Refresh();
                string abc = _myform.dataGridView1.Rows[0].Cells[0].Value.ToString();
                _myform.label2.Text = abc;

            }

        }

但是在我定义的UserControl1中的dataGridView1中没有返回任何数据,跟踪的时候是有数据的,我用label也没有显示出数据,请教各位老师指导一下!

------解决方案--------------------
this.Controls.Add(_myform);

否则UserControl不属于窗体,当然你看不到了。
------解决方案--------------------
你可以写
UserControl1 GetExcelData()
{
   ...
   _myform.label2.Text = abc;
   return UserControl1;
}
主程序:
this.Controls.Add(GetExcelData());