【问题标题】:how to get specific colums from datagridview to listbox如何从datagridview获取特定列到列表框
【发布时间】:2017-12-07 19:45:15
【问题描述】:

我试图将 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++;
        }
    }

【问题讨论】:

  • 我想要 2 3 和 15 列

标签: c# datagridview listbox


【解决方案1】:
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++;
    }
}

【讨论】:

  • 感谢您的回复我有一个例外'索引超出范围。必须是非负数且小于集合的大小。参数名称:index'
  • 对不起,我在最初的回答中有一个错误。我已经更新了索引,你现在可以再试一次吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 2011-07-31
  • 2017-06-16
  • 2023-03-22
  • 1970-01-01
相关资源
最近更新 更多