想要在datagridview中将所选价格显示为标签。目前,我正在使用循环显示价格,但它只给我第一个选定的价格。
显示价格的代码
int selectedCellCount = dataGridView1.GetCellCount(DataGridViewElementStates.Selected);
if (selectedCellCount > 0)
{
for (int i = 0; i < selectedCellCount; i++)
{
int row = dataGridView1.SelectedCells[i].RowIndex;
label3.Text = dataGridView1.Rows[row].Cells[3].Value.ToString();
}
}
我该如何计算输入数量的总价
答案 0 :(得分:1)
我想我从您对一个答案的评论中得到您的意思。您希望每当选择行时,所选行的价格都显示在标签中?是的。
为此,您可以使用名为SelectionChanged()的DataGridView事件,因此只要您的选择发生更改,此事件就会触发并更改您的标签。
假设您的gridview只允许一个选择。
private void DataGridView1_SelectionChanged(object sender, EventArgs e)
{
DataGridViewRow row = this.dataGridView1.SelectedRows[0];
label.Text = row.Cells[3].Value.ToString();
}
希望这对您有所帮助。
答案 1 :(得分:0)
尝试一下
List<int> indexes = dataGridView1.SelectedRows.Cast<DataGridViewRow>().Select(x => Select(x => x.Index).ToList();
int sum = 0;
for (int i = 0; i < indexes.Count; i++)
{
// here the label text will be the last row price because you overwrite each time
label3.Text = dataGridView1.Rows[i].Cells[3].Value.ToString();
sum += int.Parse(dataGridView1.Rows[i].Cells[3].Value.ToString());
}
MessageBox.Show("Sum of selected rows = " + sum.ToString());
答案 2 :(得分:0)
这是答案。谢谢大家
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count > 0) // make sure user select at least 1 row
{
label3.Text = dataGridView1.SelectedRows[0].Cells[3].Value + string.Empty;
}