从c#中的数组中读取

时间:2012-11-24 17:14:34

标签: c# arrays textbox

我非常接近让这个工作正常,但我只是遗漏了一些东西。这可能很简单。我对C#很新。我有一个名为txtState的文本框,您输入一个城市(我知道),看看您是否访问了这个城市。当您单击txtAnswer按钮时,它会向另一个文本框btnVisited输出响应。现在它只是输入我在txtState框中输入的内容,并说它是数组中的0位置。我忘了提到我需要在这个城市的数组中包含什么位置,并将其输出到文本框中。这是我的代码:

namespace Test
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        txtAnswer.Text = "";
        txtState.Text = "";
    }

    private void button3_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    private void btnVisited_Click(object sender, EventArgs e)
    {
        string[] CityName = {"Columbus", "Bloomington", "Indianapolis",
        "Fort Wayne", "Greensburg", "Gary", "Chicago", "Atlanta", "Las Vegas"};
        bool visitedbool;
        int subscript;
        subscript = 0;
        visitedbool = false;
        string QueryCity;
        QueryCity = txtState.Text.ToUpper();
        do 
        {
            subscript += 0;
            if (subscript == 0)
                txtAnswer.Text = "You have visited" + " " + QueryCity + " " + "It is the" + " " + subscript + " " + "city you have visited.";

            else if (subscript == 1)
                txtAnswer.Text = "You have visited" + " " + QueryCity + " " + "It is the" + " " + subscript + " " + "st city you have visited.";

            else if (subscript == 2)
                txtAnswer.Text = "You have visited" + " " + QueryCity + " " + "It is the" + " " + subscript + " " + "nd city you have visited.";

            else if (subscript == 3)
                txtAnswer.Text = "You have visited" + " " + QueryCity + " " + "It is the" + " " + subscript + " " + "rd city you have visited.";

            else if (subscript == 4 - 8)
                txtAnswer.Text = "You have visited" + " " + QueryCity + " " + "It is the" + " " + subscript + " " + "th city you have visited.";

            else
                txtAnswer.Text = "You have not visited this city.";
        }
        while (visitedbool == true);       
    }
}
}

1 个答案:

答案 0 :(得分:1)

您的代码首次出现问题:

这不起作用:else if (subscript == 4 - 8)

请改为:else if (subscript >= 4 && subscript <= 8)

<强>第二

subscript += 0;subscript = subscript + 0;

相同

如果您使用下标作为某种计数器,那么因为您只是添加0

而无法使用

<强>第三

visitedbool始终为false。您的循环只会运行一次,因为您从未将visitedbool设置为true