如何在 C# 中将所有选中的行数据放入另一个形式的文本框中
本文关键字:另一个 文本 数据 | 更新日期: 2023-09-27 18:36:27
我有一个数据网格视图,第一列是复选框列。我们想要的是当用户选中行时,所有选中的行都应转到另一个表单中的文本框。为此,我写了以下内容。但问题是,尽管选中了 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
的行和单元格集合。它最终变得更加干净,更易于维护。例如,当您遍历所需的列时,您假定永远不会添加另一列。
接下来 - 尝试按名称而不是索引引用列。在维护代码时,它远没有那么脆弱。
您检查复选框是否被选中的检查不正确 - 如果用户选中该框然后删除检查,您仍然会计算它。您需要检查空值,如果不是空值,请检查 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();
}
}
}
}