如何从datagridview获取特定的列到列表框

时间:2017-12-07 11:21:48

标签: c# datagridview listbox

我试图获得3列而不是15列表框,我该怎么做?

这是获取所有列的代码。

private void testlist()
    {
        string[,] Datavalue = new string[dataGridView1.Rows.Count, dataGridView1.Columns.Count];
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            foreach (DataGridViewColumn col in dataGridView1.Columns)
            {
                Datavalue[row.Index, col.Index] = dataGridView1.Rows[row.Index].Cells[col.Index].Value.ToString();
            }
        }
        int i = 1;
        string strval = "";
        foreach (string ss in Datavalue)
        {
            strval += ss + " ";
            if (i == 15)
            {
                listBox1.Items.Add(strval);
                strval = "";
                i = 0;
            }
            i++;
        }
    }

1 个答案:

答案 0 :(得分:0)

private void testlist()
{
    string[,] Datavalue = new string[dataGridView1.Rows.Count, 3];
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        Datavalue[row.Index, 0] = 
            dataGridView1.Rows[row.Index].Cells[1].Value.ToString();
        Datavalue[row.Index, 1] = 
            dataGridView1.Rows[row.Index].Cells[2].Value.ToString();
        Datavalue[row.Index, 2] = 
            dataGridView1.Rows[row.Index].Cells[14].Value.ToString();
    }
    int i = 1;
    string strval = "";
    foreach (string ss in Datavalue)
    {
        strval += ss + " ";
        if (i == 3)
        {
            listBox1.Items.Add(strval);
            strval = "";
            i = 0;
        }
        i++;
    }
}