如何在二维数组中保存用户在文本框中输入的数字?
例如:
我在文本框中有这个数字:45,78 现在我想像这样保存45,32:array [0,0] = 45和array [0,1] = 78
我该怎么办呢?非常感谢
编辑: 哦,当我在文本框中输入1,2,3,4,5,6,7,8,9并且需要[2,2] = 56
private void button10_Click(object sender, EventArgs e)
{
int matrixDimention = 2;
int[,] intValues = new int[matrixDimention + 1, matrixDimention + 1];
string[] splitValues = textBox9.Text.Split(',');
for (int i = 0; i < splitValues.Length; i++)
intValues[i % (matrixDimention + 1), i % (matrixDimention + 1)] = Convert.ToInt32(splitValues[i]);
string a=intValues[2,2].ToString();
MessageBox.Show(a);
}
当我采取:
string a=intValues[2,1].ToString();
显示0
答案 0 :(得分:2)
请查看使用String.Split Method (Char[])和Convert.ToInt32 Method (String)
像
这样的东西string textBox = "45,78";
int[,] values = new int[1,2];
string[] textBoxSplit = textBox.Split(',');
values[0, 0] = Convert.ToInt32(textBoxSplit[0]);
values[0, 1] = Convert.ToInt32(textBoxSplit[1]);
修改强>
使用List和Linq的示例
string textBox = "45,78,1,2,3,4,5,6,7,8,9,10,11,12";
List<int> list = new List<int>(textBox.Split(',').Select(x => Convert.ToInt32(x)));
编辑2
使用List和foreach
的Longwinded示例string textBox = "45,78,1,2,3,4,5,6,7,8,9,10,11,12";
List<int> list2 = new List<int>();
string[] splitVals = textBox.Split(',');
foreach (string splitVal in splitVals)
list2.Add(Convert.ToInt32(splitVal));
修改强>
输入矩阵
string textBox = "1,2,3,4,5,6,7,8,9";
int matrixDimention = 2;
int[,] intValues = new int[matrixDimention + 1, matrixDimention + 1];
string[] splitValues = textBox.Split(',');
for (int i = 0; i < splitValues.Length; i++)
intValues[i/(matrixDimention + 1), i%(matrixDimention + 1)] = Convert.ToInt32(splitValues[i]);
修改强>
跟随白兔
string textBox = "1,2,3,4,5,6,7,8,9";
int matrixDimention = 2;
int[,] intValues = new int[matrixDimention + 1, matrixDimention + 1];
string[] splitValues = textBox.Split(',');
for (int i = 0; i < splitValues.Length; i++)
intValues[i/(matrixDimention + 1), i%(matrixDimention + 1)] = Convert.ToInt32(splitValues[i]);
string displayString = "";
for (int inner = 0; inner < intValues.GetLength(0); inner ++)
{
for (int outer = 0; outer < intValues.GetLength(1); outer++)
displayString += String.Format("{0}\t", intValues[inner, outer]);
displayString += Environment.NewLine;
}
MessageBox.Show(displayString);
答案 1 :(得分:1)
试试这个假设数组是一个字符串数组
str[] input = textBox.Text.Split(',');
if(input.Length > 1)
{
arr[0,0] = input[0];
arr[0,1]= input[1];
}