C# 将标签分配给数组时,索引超出了数组的边界

C# 将标签分配给数组时,索引超出了数组的边界,c#,C#,将标签分配给数组时,索引超出了数组的边界 string[] SalesReferenceArray = {}; int i=0; if (chk_Select.Checked == true) { SalesReferenceArray[i] = Convert.ToString((Label)grdSales.FindControl("lblSalesReference")); i++; } 您的数组为空,即它没有任何项。尝试访问第一个项(即索引0处的项)会导致IndexO

将标签分配给数组时,索引超出了数组的边界

string[] SalesReferenceArray = {};
int i=0;
if (chk_Select.Checked == true)
{
    SalesReferenceArray[i] = Convert.ToString((Label)grdSales.FindControl("lblSalesReference"));
     i++;
}
您的数组为空,即它没有任何项。尝试访问第一个项(即索引0处的项)会导致IndexOutfrange错误,因为项的索引应为非负且小于数组长度

如果您只需要一个项目,那么您根本不需要数组。只需声明字符串类型的变量:

string[] SalesReferenceArray = {};
如果要动态添加/删除项目,请使用列表而不是数组:

string SalesReference;
List salesferences=new List();
if(chk_Select.Checked)//不与true比较
{
字符串引用=Convert.ToString((Label)grdSales.FindControl(“lblSalesReference”);
SalesReferences.Add(reference);
}
注意:我认为您需要使用Label.Text,而不是尝试将Label转换为字符串

您的数组为空,即它没有任何项。尝试访问第一个项(即索引0处的项)会导致IndexOutfrange错误,因为项的索引应为非负且小于数组长度

如果您只需要一个项目,那么您根本不需要数组。只需声明字符串类型的变量:

string[] SalesReferenceArray = {};
如果要动态添加/删除项目,请使用列表而不是数组:

string SalesReference;
List salesferences=new List();
if(chk_Select.Checked)//不与true比较
{
字符串引用=Convert.ToString((Label)grdSales.FindControl(“lblSalesReference”);
SalesReferences.Add(reference);
}

注意:我认为您需要使用Label.Text,而不是尝试将Label转换为字符串。

您正在创建一个大小为0的空数组,即,您使用的是简写赋值语法,而不是指定任何元素

您需要通过更改代码以指定大小来修复代码,如下所示:

List<string> SalesReferences = new List<string>();
if (chk_Select.Checked) // don't compare with true
{
    string reference = Convert.ToString((Label)grdSales.FindControl("lblSalesReference"));
    SalesReferences.Add(reference);
}
如果您事先不知道阵列的大小,则可能需要使用:

List salesferencelist=new List();
if(chk_Select.Checked==true)
{
salesReferenceList.Add(Convert.ToString((标签)grdSales.FindControl(“lblSalesReference”));
}

您正在创建一个大小为0的空数组,也就是说,您使用的是简写赋值语法,没有指定任何元素

您需要通过更改代码以指定大小来修复代码,如下所示:

List<string> SalesReferences = new List<string>();
if (chk_Select.Checked) // don't compare with true
{
    string reference = Convert.ToString((Label)grdSales.FindControl("lblSalesReference"));
    SalesReferences.Add(reference);
}
如果您事先不知道阵列的大小,则可能需要使用:

List salesferencelist=new List();
if(chk_Select.Checked==true)
{
salesReferenceList.Add(Convert.ToString((标签)grdSales.FindControl(“lblSalesReference”));
}

列表更适合您,因为它是动态的

List<string> salesReferenceList = new List<string>();

if (chk_Select.Checked == true)
{
    salesReferenceList.Add(Convert.ToString((Label)grdSales.FindControl("lblSalesReference")));
}

列表更适合您,因为它是动态的

List<string> salesReferenceList = new List<string>();

if (chk_Select.Checked == true)
{
    salesReferenceList.Add(Convert.ToString((Label)grdSales.FindControl("lblSalesReference")));
}

如何声明动态array@KrishnaPrabha使用列表,如上所述,如何声明动态array@KrishnaPrabha使用列表,正如我上面提到的