在我的表单上,一个标签应该显示数组中的所有名称,然后第二个数组应该根据数组中的位置更改名称。
以下是我使用的代码:
location = int.Parse(txtLocation.Text);
name = Convert.ToString(txtName.Text);
string[] strOriginalNames = new string[4]; // Declares a new string variable called strOriginalNames
strOriginalNames[0] = "John";
strOriginalNames[1] = "Paul";
strOriginalNames[2] = "Rodney"; // Set values to each element in the array
strOriginalNames[3] = "David";
strOriginalNames[4] = "Kathryn";
foreach (string originalName in strOriginalNames)
{
lblOriginalNames.Text += originalName + "<br>";
}
strOriginalNames(location) = (name);
foreach (string newName in strOriginalNames)
{
lblNewNames.Text += newName + "<br>";
}
唯一的错误是使用此代码段:
strOriginalNames(location) = (name);
以下是我的表单截图:
要使代码正确运行,应在新数组
下将数组中的第二个元素更改为Andrew有谁知道如何纠正我的代码中的错误?
答案 0 :(得分:1)
尝试
strOriginalNames[location] = name;
答案 1 :(得分:0)
为了您的利益,因为Martin已经正确而简洁地回答,您可以像这样编写代码:
location = int.Parse(txtLocation.Text);
name = Convert.ToString(txtName.Text);
string[] strOriginalNames = new[] { "John", "Paul", "Rodney", "David", "Kathryn" };
lblOriginalNames.Text = String.Join("<br>", strOriginalNames);
strOriginalNames[location] = name;
lblNewNames.Text = String.Join("<br>", strOriginalNames);
稍微不同的是,最后一个元素后面没有"<br>"
,但我认为这可能是你想要的。