从arrayList中获取值

Rya*_*ard 3 c# arraylist

我正在使用C#,我正在创建一个名为"importControlKeys"的ArrayList,它可以很好地创建.但是,我无法为我的生活找到一种方法来遍历arrayList并选择ArrayList中的值以便在以后的代码中使用.

我知道我遗漏了一些简单的东西,但是从ArrayList中提取值的语法是什么.我希望它在某些情况下像我的代码中的importControlKeys [ii] .value,但这不起作用.

我在这些电路板上搜索过,找不到确切的解决方案,但我确信它很容易.msot的解决方案说重写为List但我不得不相信有一种方法可以从数组列表中获取数据而无需重新编写为List

private void button1_Click(object sender, EventArgs e)
        {
            ArrayList importKeyList = new ArrayList();
            List<DataGridViewRow> rows_with_checked_column = new List<DataGridViewRow>();
            foreach (DataGridViewRow row in grd1.Rows) 
            { 
                if (Convert.ToBoolean(row.Cells[Del2.Name].Value) == true)
                { 
                    rows_with_checked_column.Add(row);
                    importKeyList.Add(row.Cells[colImportControlKey.Name].Value);

                    //string importKey = grd1.Rows[grd1.SelectedCells[0].RowIndex].Cells[0].Value.ToString();
                    //grd1.ClearSelection();
                    //if (DeleteImport(importKey))
                    //    LoadGrid();
                }                
            }
            for (int ii = 0; ii < rows_with_checked_column.Count; ii++)
            {
                //grd1.ClearSelection();
                string importKey = importKeyList[ii].value;  //ERRORS OUT

                if (DeleteImport(importKey))
                    LoadGrid();

                // Do what you want with the check rows  
            }

        }
Run Code Online (Sandbox Code Playgroud)

Met*_*Man 6

不确定为什么要使用ArrayList,但是如果你需要循环它,你可以做这样的事情

如果一个元素不能转换为该类型,您将获得InvalidCastException.在您的情况下,您不能将boxed int强制转换为字符串,从而导致抛出异常.

foreach (object obj in importKeyList ) 
{
    string s = (string)obj;
    // loop body
}
Run Code Online (Sandbox Code Playgroud)

或者你做一个for循环

for (int intCounter = 0; intCounter < importKeyList.Count; intCounter++)
{
    object obj = importKeyList[intCounter];
    // Something...
}
Run Code Online (Sandbox Code Playgroud)