c# -基于零的字符串错误

本文关键字:字符串 错误 于零 | 更新日期: 2023-09-27 18:11:35

当我尝试登录时出现这个错误。

索引(从零开始)必须大于或等于零且小于实参列表的大小。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        //string name = textBox1.Text;
        string.Format ("{0} {1}", "Best", "Regards");
        if (textBox1.Text == "Ryan" && textBox2.Text == "password")
        {
            MessageBox.Show(string.Format("Welcome {1}" ));
        }
    }
}

c# -基于零的字符串错误

string.Format("Welcome {1}" )

需要参数

string.Format("Welcome {0}", textBox1.Text )

在这一行抛出错误:

MessageBox.Show(string.Format("Welcome {1}" ));

,因为您使用了占位符{1},但没有为string.Format函数提供参数。除此之外,您还没有从索引0开始。

你必须提供一个参数,并从索引0开始:

MessageBox.Show(string.Format("Welcome {0}", textBox1.Text));

您需要做以下操作:

string.Format("Welcome {0}", "some value here");
MessageBox.Show(string.Format("Welcome {0}", "some text"));