I have a grid view with 10 rows.
After clicking on a button I would like to check and make sure each cell value are the same or not under the firstname
column of gridview
.
If all the cell values are same then call the changeCellValues()
method. If any cell value is different then MessageBox.Show("You cant use your method");
private void button1_Click(object sender, EventArgs e)
{
string x;
string y;
x = dataGridView1.Rows[0].Cells[1].Value.ToString();
for (int i = 0; i < 11; i++)
{
y = dataGridView1.Rows[i].Cells[1].Value.ToString();
if (x == y) continue;
MessageBox.Show("You cant use your method");
}
}
How can I check if column value same on every row on GridView?
If you have 10
rows, change i < 11
to i < 10
and start i
from 1
because you already get the first row's value and store it into x
.Your way seems correct but instead of displaying the messagebox inside of the loop, you can use something like this:
x = dataGridView1.Rows[0].Cells[1].Value.ToString();
bool control = true;
for (int i = 1; i < 10; i++)
{
y = dataGridView1.Rows[i].Cells[1].Value.ToString();
if (x != y) { control = false; break; }
}
if(!control) MessageBox.Show("You cant use your method");
else changeCellValues();
Alternative using LINQ... grab everything in the column "firstname", remove duplicates using Distinct
, and then count the number of unique names. (If you have more than 1 unique name, they're not all the same.)
var isSameName = dataGridView1.Rows.Cast<DataGridViewRow>()
.Select(x => Convert.ToString(x.Cells["firstname"].Value))
.Distinct().Count() == 1;
if (!isSameName)
{
MessageBox.Show("You cant use your method");
return;
}
changeCellValues();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.