繁体   English   中英

如何在C#中使gridview将所有检查的行数据放入另一种形式的文本框中?

[英]How to get gridview all checked row data into textboxes of another form in C#?

我有一个数据网格视图,其中复选框列为第一列。 我们想要的是当用户选中行时,所有选中的行都应转到另一个“表单”中的文本框。 我写了以下文章。 但是问题是尽管检查了多于1行,但总是将最后检查的行数据发送到下一个表单。 并非所有选中的行数据

private void btngnvoucher_Click(object sender, EventArgs e)
{
    // foreach(DataGridViewRow row in dataGridView1.Rows)
    for (int x = 0; x < dataGridView1.RowCount;x++ )
    {
        // DataGridViewCheckBoxCell ch1  = (DataGridViewCheckBoxCell)row.Cells[0];
        DataGridViewCheckBoxCell ch1 = (DataGridViewCheckBoxCell)dataGridView1.Rows[x].Cells[0];

        if (ch1.Value != null)
        {
            for (int a = 0; a < 6; a++)
            {
                for (int col = 1; col < 5; col++)
                {
                    TextBox theText1 = (TextBox)vobj.Controls[col - 1];

                    // theText1.Text = row[x].Cells[col].Value.ToString();
                    theText1.Text = dataGridView1.Rows[x].Cells[col].Value.ToString();

                }

                // a = a + 1;
                break;

            }
        }
    }

    vobj.Show();
}
}

}

谁能告诉我该如何解决?

代替这个:

theText1.Text = dataGridView1.Rows[x].Cells[col].Value.ToString();

尝试:

theText1.AppendText(dataGridView1.Rows[x].Cells[col].Value.ToString());

问题的原因似乎是您打算让变量a进行某些操作,但不对其执行任何操作。 看起来这意味着要引用一行文本框,然后由在单元格上方查看的代码填充这些文本框。

按照目前的代码:

for (int col = 1; col < 5; col++)
{
    TextBox theText1 = (TextBox)vobj.Controls[col - 1];

    // theText1.Text = row[x].Cells[col].Value.ToString();
    theText1.Text = dataGridView1.Rows[x].Cells[col].Value.ToString();

}

为每一行填充相同的四个文本框。


就是说,您的代码还有很多其他问题,这些问题在修复后可能会使您更清楚。

首先-尽可能使用foreach循环遍历DataGridView的行和单元格集合。 最终,它变得更加干净和易于维护。 例如,当您遍历所需的列时,您假定永远不会添加另一列。

接下来-尝试通过名称而不是索引来引用列。 维护代码时它不那么脆弱。

您查看复选框是否被选中的检查是不正确的-如果用户先选中该复选框然后再删除该支票,您的处理方式将仍然计数。 您需要检查是否为null,如果不为null,则检查true。

通过这些更改,您将获得以下内容:

foreach (DataGridViewRow r in dataGridView1.Rows)
{
    if (r.Cells["CheckBox"].Value != null && (bool)r.Cells["CheckBox"].Value)
    {
        foreach (DataGridViewCell c in r.Cells)
        {
            if (c.ValueType == typeof(string))
            {
                // The code here is still ugly - there is almost certainly
                // a better design for what you are trying to do but that is
                // beyond the scope of the question.
                // Plus it still has your original bug of referencing the 
                // same row of text boxes repeatedly.
                TextBox theText1 = (TextBox)vobj.Controls[c.ColumnIndex];
                theText1 += c.Value.ToString();
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM