从另一列中获取与某些值相关的Datagridview的值c#(Get Values from Datagridview related to to certain values in another column c#)

所以这是我的问题。 我没有编码很长时间,我已经在这个问题上拉了我的头发2天了,不能得到一个有效的答案......

Form1具有包含3列和多行数据的datagridview。 如果我按下Form1上的一个按钮,我需要它填充第1列中列[2]中具有特定值的所有值,然后将其显示在Form2上的文本框中。

例:

Datagrid示例

因此,如果我单击一个按钮,我想拉出car1的所有金额,并在form2的文本框中显示总数。

Form2 obj = new Form2(); public void button4_Click(object sender, EventArgs e) { String searchValue = "Car1"; int rowIndex = 1; foreach (DataGridViewRow row in dataGridView1.Rows) { if (row.Cells[2].Value.ToString().Equals(searchValue)) { rowIndex = row.Index; obj.Controls["TextBox1"].Text = dataGridView1.Rows[rowIndex].Selected.ToString(); obj.Show(); } else { break; } } }

我只是在我的文本框中得到了“真实”的答案

我希望这是有道理的

提前致谢

So here is my problem. I have not been coding very long and i have been pulling my hair out on this issue for 2 days now and cant get an answer that works...

Form1 has a datagridview with 3 columns and multiple rows of data. If i press a button on Form1 i need it to populate all the values in column1 that has a certain value in column[2] and then display it in a textbox on Form2.

Example:

Datagrid example

So if I click a button i want to pull all the amounts for car1 and display the total in a textbox on form2.

Form2 obj = new Form2(); public void button4_Click(object sender, EventArgs e) { String searchValue = "Car1"; int rowIndex = 1; foreach (DataGridViewRow row in dataGridView1.Rows) { if (row.Cells[2].Value.ToString().Equals(searchValue)) { rowIndex = row.Index; obj.Controls["TextBox1"].Text = dataGridView1.Rows[rowIndex].Selected.ToString(); obj.Show(); } else { break; } } }

I just get the answer "true" in my textbox

I hope this makes sense

Thanks in advance

最满意答案

你为什么打破foreach循环。 据我了解,你需要所有其他数量的Car1。 对? 看一下这个:

Form2 obj = new Form2(); public void button4_Click(object sender, EventArgs e) { String searchValue = "Car1"; int amount = 0; foreach (DataGridViewRow row in dataGridView1.Rows) { if(row.Cells["Type"].Value.ToString().Equals(searchValue) { amount+ = Convert.ToInt32(row.Cells["Amount"].Value.ToString()) } } if(amount > 0 ) { obj.Controls["TextBox1"].Text = amount.ToString(); } else { obj.Controls["TextBox1"].Text = "No car found!"; } obj.Show(); }

您还需要控制金额是否为数字。

Why do you break foreach loop. As i understand, you want all other amounts of Car1. Right? Check this out:

Form2 obj = new Form2(); public void button4_Click(object sender, EventArgs e) { String searchValue = "Car1"; int amount = 0; foreach (DataGridViewRow row in dataGridView1.Rows) { if(row.Cells["Type"].Value.ToString().Equals(searchValue) { amount+ = Convert.ToInt32(row.Cells["Amount"].Value.ToString()) } } if(amount > 0 ) { obj.Controls["TextBox1"].Text = amount.ToString(); } else { obj.Controls["TextBox1"].Text = "No car found!"; } obj.Show(); }

Also you need to control if Amount is a number or not.

更多推荐