c#窗體間的傳值

窗體:父和子
值:字符等一般值,數組等值
1.父<---值---子(MDIParentin_add
父窗體接受值代碼:
in_add in1 = new in_add();
if (in1.ShowDialog() == DialogResult.OK)
            {
                showIN();   子窗體成功後,返回,父窗體將執行的代碼
            }
子窗體是這麼發送值的:
this.DialogResult = DialogResult.OK;

2。父---值--->子(Form1Form2
父窗體中定義一子類
            Form2 form2 = new Form2();
            form2.ShowDialog(this);
            form2.Dispose();

不用專門發送值,只要存在的這個值是public的,子窗體就有權獲得
在子窗體中定義一個父類,如下:
            Form1 form1 = new Form1();
            form1 = (Form1)this.Owner;

C#窗體中,數據一般用到數據控件,比如dataGridView,這個控件的值一般是一行或則一列的數的集合,所以用到數組。在開發的時候,容易設計到集合的值到數組的複製。
這裏的數值一般是二維數值
父窗體中的數值聲明:public string[,] strs = new string[1 ,4];
父窗體將dataGridView的集合賦予一個二維數組strs= ToStringArray(this.dataGridView1, true);
public string[,] ToStringArray(DataGridView dataGridView, bool includeColumnText)
        {
            #region 實現...
            string[,] arrReturn = null;
            int rowsCount = dataGridView.Rows.Count;
            int colsCount = dataGridView.Columns.Count;
            if (rowsCount > 0)
            {
                //最後一行是供輸入的行時,不用讀數據。
                if (dataGridView.Rows[rowsCount - 1].IsNewRow)
                {
                    rowsCount--;
                }
            }
            int i = 0;
            //包括列標題
            if (includeColumnText)
            {
                rowsCount++;
                arrReturn = new string[rowsCount, colsCount];
                for (i = 0; i < colsCount; i++)
                {
                    arrReturn[0, i] = dataGridView.Columns[i].HeaderText;
                }
                i = 1;
            }
            else
            {
                arrReturn = new string[rowsCount, colsCount];
            }
            //讀取單元格數據
            int rowIndex = 0;
            for (; i < rowsCount; i++, rowIndex++)
            {
                for (int j = 0; j < colsCount; j++)
                {
                    arrReturn[i, j] = dataGridView.Rows[rowIndex].Cells[j].Value.ToString();
                }
            }
            return arrReturn;
            #endregion 實現
        }

子窗體接受二維數組:
string[,] str=form1.strs;   父窗體的strs
            for (int i = 0; i < str.GetLength(0); i++)
                for (int j = 0; j < str.GetLength(1);j++ )
                    this.label1.Text += str[i,j];

總結:數組在窗體間的傳遞!

發佈了14 篇原創文章 · 獲贊 2 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章