将VS.Net 2005 DataGridView控件的数据导出到二维数组

///
/// 将VS.Net 2005 DataGridView控件的数据导出到二维数组。
///
/// VS.Net 2005 DataGridView控件。
/// 是否要把列标题文本也导到数组中。
/// <作者>长江支流
/// <日期>
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 实现
}

//对两维数组的重新学习
//二维数组转换成一维数组(C#版本)
using System;
namespace ConsoleApplication1
{
    
class Program
    {
        
private static void TwoarrTrancteOnearr(int m,int n)
        {
            
int[,] arr2;
            
int[] arr1;
            arr2 
= new int[m, n];
            arr1 
= new int[m*n];
          
            Console.WriteLine(
"output value of arr2:");
            
for (int i = 0; i < m; ++i)
            {
                
for (int j = 0; j < n; ++j)
                {
                    arr2[i, j] 
= i * n + j;
                    Console.Write(
"{0} ",arr2[i, j]);
                }
                Console.WriteLine();
            }

           Console.WriteLine(
"Output value of arr1:");       
            
for(int i=0;i<m*n;++i)
            {
                
int r = i / n;
                
int c = i % n;
                arr1[i] 
= arr2[r, c];
                Console.Write(
"{0} ",   arr1[i]);
            }
            Console.WriteLine();
            Console.WriteLine(
"Press <enter> key exit!");
            Console.ReadLine();
        }
        
static void Main(string[] args)
        {
            TwoarrTrancteOnearr(
43);
        }
    }
}

string[][] fn=new string[2][];

fn[
0]=new string[]{2,3}
fn[
1]=new string[]{4,5}


posted @ 2006-12-28 23:26  wenanry  阅读(1226)  评论(1编辑  收藏  举报