c#代码错误名称“i”不存在

时间:2010-12-28 09:12:22

标签: c#

在行

 urls[i] =  Reader.GetValue(i).ToString();  

它说错误1当前上下文中不存在名称“i”

我该如何解决?

private void Form1_Load(object sender, EventArgs e)
    {
        string MyConString = "SERVER=192.168.0.78;" +
             "DATABASE=webboard;" +
             "UID=aimja;" +
             "PASSWORD=aimjawork;" +
             "charset=utf8;";
        MySqlConnection connection = new MySqlConnection(MyConString);
        MySqlCommand command = connection.CreateCommand();
        MySqlDataReader Reader;
        command.CommandText = "SELECT  url FROM `listweb` WHERE `url` IS NOT NULL AND ( `webbordkind` = '¿¿¿¿¿¿¿¿¿¿¿¿' ) and `nourl`= 'n' order by province, amphore limit 4 ";
        connection.Open();
        Reader = command.ExecuteReader();


        string[] urls = new string[2];
        string thisrow = "";
        string sumthisrow = "";
        string urlname ;
        while (Reader.Read())
        {
            thisrow = "";
            for (int i = 0; i < Reader.FieldCount; i++)
                thisrow +=  Reader.GetValue(i).ToString();
                urlname = Reader.GetValue(i).ToString();

                urls[i] =  Reader.GetValue(i).ToString(); 

          //  System.IO.File.AppendAllText(@"C:\file.txt", thisrow + " " + Environment.NewLine);
            sumthisrow = sumthisrow + thisrow;

3 个答案:

答案 0 :(得分:5)

您需要在for循环中添加大括号,否则它只会循环第一个语句。

for (int i = 0; i < Reader.FieldCount; i++)
{
    thisrow +=  Reader.GetValue(i).ToString();
    urlname = Reader.GetValue(i).ToString();
    urls[i] =  Reader.GetValue(i).ToString(); 
}

答案 1 :(得分:3)

你在这里缺少大括号:

for (int i = 0; i < Reader.FieldCount; i++)
{
    thisrow +=  Reader.GetValue(i).ToString();
    urlname = Reader.GetValue(i).ToString();
    urls[i] = Reader.GetValue(i).ToString(); 
}

我还建议你通过在循环中连接来创建字符串。首先将它们放在List<string>中,然后将其转换为数组(.NET 4.0或更高版本除外,不需要此步骤)并使用string.Join。除了提供更好的性能之外,这允许您在字段之间添加分隔符,我认为您想要...

如果您不需要分隔符,则可以使用StringBuilder。

答案 2 :(得分:1)

FOR循环缺少大括号。变量i仅在FOR循环中可用,在你的循环中只有一行。

for (int i = 0; i < Reader.FieldCount; i++)
{
    thisrow +=  Reader.GetValue(i).ToString();
    urlname = Reader.GetValue(i).ToString();

    urls[i] =  Reader.GetValue(i).ToString();
}