【发布时间】:2016-03-31 07:05:17
【问题描述】:
我有一个名为 PTable 的数据网格视图,它显示数据库中的一个表。我还有一个按钮,可以将数据从选定的行复制到我拥有的文本框中。
我现在拥有的这段代码从 datagridview 复制两个选定的行,但是当我只选择一行或选择超过 2 行时,它说“索引超出范围”
应该发生的是它应该复制任意数量的行,而不仅仅是 2 行
private void button11_Click(object sender, EventArgs e)
{
productid.Text = PTable.SelectedRows[0].Cells[0].Value + string.Empty;
productname.Text = PTable.SelectedRows[0].Cells[1].Value + string.Empty;
unitprice.Text = PTable.SelectedRows[0].Cells[4].Value + string.Empty;
productid2.Text = PTable.SelectedRows[1].Cells[0].Value + string.Empty;
productname2.Text = PTable.SelectedRows[1].Cells[1].Value + string.Empty;
unitprice2.Text = PTable.SelectedRows[1].Cells[4].Value + string.Empty;
}
【问题讨论】:
-
不需要
+ string.Empty。删除它们。您有多少 productidx productnamex unitpricex 文本框?将它们放入列表中 -
首先将DataGridView的SelectionMode改为FullRowSelect。否则用户可能会选择单元格而不是行,并且代码将不起作用
-
@ntohl 好的。我将删除 string.Empty。我在 datagridview 上有 3 行,但添加新产品时会更多。我有 5 个文本框。
-
也使用代码进行 NULL 检查。
-
@codetoshare 已经在 FullRowSelect 中
标签: c# datagridview