PDA

View Full Version : سوال: حذف سطرهای دیتاگریدویو بر اساس تکرار یک سلول خاص



forodo
سه شنبه 19 فروردین 1393, 09:53 صبح
سلام
چطور می تونم بر اساس یک سلول سطرهای تکراری رو حذف کنم.
یعنی مثلاً من 4تا ستون دارم ولی می خوام براساس یک ستون که عدد در اون هستش اون سطرهایی که تکراری هستند رو حذف کنم.
مثلاً سطر اول :
22 - علی
سطر دوم:
23 - رضا
سطر سوم:
22 - محمد
بعد از حذف فقط سطر اول و دوم بمونه یا سطر دو و سوم.
با تشکر

forodo
سه شنبه 19 فروردین 1393, 10:00 صبح
اینو پیدا کردم ولی فقط سطر اول رو چک می کنه و با بقیه سطرها کاری نداره.
یعنی سطر اول اگه 1 باشه فقط اونایی که 1 دارن رو پاک می کنه و برای سطر دوم جستجویی قرار نمی ده.

List<string> list = new List<string>();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
string str = dataGridView1.Rows[i].Cells[0].Value.ToString();
if (!list.Contains(str))
list.Add(dataGridView1.Rows[i].Cells[0].Value.ToString());
else
{
dataGridView1.Rows.Remove(dataGridView1.Rows[i]);
}
}

عددام اینطوریه:

private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.Rows.Add("1");
dataGridView1.Rows.Add("2");
dataGridView1.Rows.Add("3");
dataGridView1.Rows.Add("1");
dataGridView1.Rows.Add("2");
dataGridView1.Rows.Add("1");
dataGridView1.Rows.Add("3");
}

Davidd
سه شنبه 19 فروردین 1393, 10:49 صبح
List<string> list = new List<string>();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
string str = dataGridView1.Rows[i].Cells[0].Value.ToString();
if (!list.Contains(str))
list.Add(dataGridView1.Rows[i].Cells[0].Value.ToString());
else
{
dataGridView1.Rows.Remove(dataGridView1.Rows[i]);
}
}





منطق كد درسته ولي به خاطر اينكه در داخل حلقه سطرهاي ديتاگريد تغيير ميكنه؛ اين كد درست كار نمي كنه. به اين صورت بنويسش :

List<string> list = new List<string>();
int i=0;
int len=dataGridView1.Rows.Count;

while(i<len)

{
string str = dataGridView1.Rows[i].Cells[0].Value.ToString();
if (!list.Contains(str)){

list.Add(dataGridView1.Rows[i].Cells[0].Value.ToString());
i++
}

else
{
dataGridView1.Rows.Remove(dataGridView1.Rows[i]);
len--;

}
}

Mahmoud.Afrad
پنج شنبه 21 فروردین 1393, 20:05 عصر
اگر اطلاعات از دیتابیس میاد از طریق کوئری میتونی انجام بدی.