怎样实现保存由winform的多个textBox获取的值组成的数组并写成int【,】的形式
比如第一次操作完窗体得到第一个数组{1,2,3,4},第二次再操作又得到了第二个数组{4,3,2,1},如何写成 int【,】array={{1,2,3,4},{4,3,2,1}}的形式,并保存在txt或者别的地方,并且下次可以提取出来array
怎样实现保存由winform的多个textBox获取的值组成的数组并写成int【,】的形式
比如第一次操作完窗体得到第一个数组{1,2,3,4},第二次再操作又得到了第二个数组{4,3,2,1},如何写成 int【,】array={{1,2,3,4},{4,3,2,1}}的形式,并保存在txt或者别的地方,并且下次可以提取出来array
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace Q1064245
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int[,] arr;
int x = 0;
int y = 0;
private void arrToTextBox(int[,] arr)
{
panel1.Controls.Clear();
x = arr.GetLength(0);
y = arr.GetLength(1);
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
TextBox txt = new TextBox();
txt.Name = string.Format("txt_{0}_{1}", i, j);
panel1.Controls.Add(txt);
txt.Top = i * 40;
txt.Left = j * 120;
txt.Text = arr[i, j].ToString();
txt.TextChanged += new EventHandler(txt_TextChanged);
}
}
}
void txt_TextChanged(object sender, EventArgs e)
{
var arr = textBoxToArr();
propertyGrid1.SelectedObject = arr;
}
private int[,] textBoxToArr()
{
int[,] arr = new int[x, y];
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
arr[i, j] = int.Parse((panel1.Controls["txt_" + i.ToString() + "_" + j.ToString()] as TextBox).Text);
}
}
return arr;
}
private void button1_Click(object sender, EventArgs e)
{
int[] dim = textBox1.Text.Split('*').Select(x => int.Parse(x)).ToArray();
arr = new int[dim[0], dim[1]];
propertyGrid1.SelectedObject = arr;
arrToTextBox(arr);
}
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog ofn = new OpenFileDialog();
if (ofn.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
var data = File.ReadAllLines(ofn.FileName).Select(x => x.Split(',').Select(y => int.Parse(y)).ToArray()).ToArray();
int[,] arr = new int[data.Count(), data[0].Count()];
for (int i = 0; i < data.Count(); i++)
{
for (int j = 0; j < data[0].Count(); j++)
{
arr[i, j] = data[i][j];
}
}
propertyGrid1.SelectedObject = arr;
arrToTextBox(arr);
}
}
private void button3_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
var arr = textBoxToArr();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < x; i++)
{
if (i != 0) sb.Append("\r\n");
for (int j = 0; j < y; j++)
{
if (j != 0) sb.Append(',');
sb.Append(arr[i, j].ToString());
}
}
File.WriteAllText(sfd.FileName, sb.ToString());
}
}
}
}