嘿,我一直收到错误:
索引(从零开始)必须大于或等于零且小于参数列表的大小。
我的代码:
OdbcCommand cmd = new OdbcCommand("SELECT FirstName, SecondName, Aboutme FROM User WHERE UserID=1", cn);
OdbcDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Name.Text = String.Format("{0} {1}", reader.GetString(0), reader.GetString(1));
Aboutme.Text = String.Format("{2}", reader.GetString(0));
}
答案 0 :(得分:169)
您的第二个String.Format
使用{2}
作为占位符,但您只传递了一个参数,因此您应该使用{0}
代替。
改变这个:
String.Format("{2}", reader.GetString(0));
对此:
String.Format("{0}", reader.GetString(2));
答案 1 :(得分:21)
在这一行:
Aboutme.Text = String.Format("{2}", reader.GetString(0));
令牌{2}无效,因为您在parms中只有一个项目。请改用:
Aboutme.Text = String.Format("{0}", reader.GetString(0));
答案 2 :(得分:6)
更改此行:
Aboutme.Text = String.Format("{0}", reader.GetString(0));
答案 3 :(得分:2)
尝试抛出ArgumentException
而无意中调用ArgumentException
构造函数重载
public static void Dostuff(Foo bar)
{
// this works
throw new ArgumentException(String.Format("Could not find {0}", bar.SomeStringProperty));
//this gives the error
throw new ArgumentException(String.Format("Could not find {0}"), bar.SomeStringProperty);
}
答案 4 :(得分:0)
using System;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
Console.WriteLine("Enter Your FirstName ");
String FirstName = Console.ReadLine();
Console.WriteLine("Enter Your LastName ");
String LastName = Console.ReadLine();
Console.ReadLine();
Console.WriteLine("Hello {0}, {1} " + FirstName, LastName);
Console.ReadLine();
}
}
}
答案 5 :(得分:0)
String.Format必须以零索引“{0}”开头,如下所示:
Aboutme.Text = String.Format("{0}", reader.GetString(0));
答案 6 :(得分:0)
更改此行:
2应该为0。每个计数都从0开始。
//Aboutme.Text = String.Format("{2}", reader.GetString(0));//wrong
//Aboutme.Text = String.Format("{0}", reader.GetString(0));//correct
答案 7 :(得分:-1)
就我而言,我看不到错误“ +名称” 。在这种情况下,编译器不会报告错误。所以要小心。
//Wrong Code:
string name="my name";
string age=25;
String.Format(@"Select * from table where name='{1}' and age={1}" +name, age);
//Right Code:
string name="my name";
string age=25;
String.Format(@"Select * from table where name='{1}' and age={1}" , name, age);