ID | SAMPLE 1 | SAMPLE 2 | SAMPLE 3 | SAMPLE 4 | SAMPLE 5
1 | cell 1 | cell 2 | cell 3 | cell 4 | cell 5
2 | cell 1 | cell 2 | cell 3 | cell 4 | cell 5
3 | cell 1 | cell 2 | cell 3 | cell 4 | cell 5
例如我有datagridview,我想获取 SAMPLE 5 下的所有单元格。 如何获取特定列下的所有单元格值? * forloop或foreach 因为我有一个条件,如果单元格的值小于48,它将被删除。
Q1:如何获取特定列下的所有单元格值 Q2:如何删除具有较少48值的单元格的整行
例如,如果在 SAMPLE 5 下有一个值为30的单元格
ID | SAMPLE 1 | SAMPLE 2 | SAMPLE 3 | SAMPLE 4 | SAMPLE 5
1 | Test | Test | Test | Test | 30
将删除整行。
这是代码:
foreach (DataGridViewRow row in dgResult1.Rows)
{
string regHrs = dgResult1.Rows[6].Cells[0].Value.ToString();
int regValue = 0;
bool regCheck = int.TryParse(regHrs, out regValue);
if ( !regCheck || Convert.ToInt32(regHrs) < 48
{
dgResult1.Rows.Remove(row);
}
else
{
dgResult1.Rows.Remove(row);
}
}
答案 0 :(得分:2)
下面是示例代码,请完成一次
下面我在winforms应用程序中获取了一个datagrid和一个按钮。在按钮单击事件中,我编写了逻辑。
基本上我们在用于循环迭代时不能删除datagrid行所以我们保存了具有单元格值&lt; 48,我们删除了那些行。
public partial class Form1 : Form
{
//Global variable to store the row numbers
List<int> rowNumbers = new List<int>();
public Form1()
{
InitializeComponent();
DataTable myDataTable = new DataTable();
// Add columns to DataTable.
myDataTable.Columns.Add("ID",typeof(int));
myDataTable.Columns.Add("Sample 1", typeof(int));
myDataTable.Columns.Add("Sample 2", typeof(int));
// Add rows to the DataTable.
myDataTable.Rows.Add(1, 10, 30);
myDataTable.Rows.Add(2, 20, 50);
myDataTable.Rows.Add(3, 20, 80);
dataGridView1.DataSource = myDataTable.DefaultView;
}
private void button1_Click(object sender, EventArgs e)
{
//Loop all rows
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
//Give the column index which you want for example below i have given 3rd column index
if (dataGridView1[2, i].Value != null)
{
int cellValue = (int)dataGridView1[2, i].Value;
//Check whether the value is less than 48 or not and store the row number in one variable
if (cellValue <= 48)
rowNumbers.Add(i);
}
}
//Remove the rows which has the cell value < 48
foreach (var item in rowNumbers)
{
dataGridView1.Rows.RemoveAt(item);
}
}
}
答案 1 :(得分:0)
List<DataGridViewRow> rowsToRemove = new List<DataGridViewRow>();
int cellIndex = 0;
foreach (DataGridViewRow row in dgResult1.Rows)
{
string regValue = row.Cells[cellIndex].Value.ToString();
if(...)
{
rowsToRemove.Add(row);
}
}
rowsToRemove.ForEach(r=>{
dgResult1.Rows.Remove(r);
});
修改强>
如何查找值小于48的列
foreach (DataGridViewRow row in dgResult1.Rows)
{
foreach (var cell in row.Cells)
{
// IF Condition (less than 48)
int columnIndex = row.Cells.IndexOf(cell);
}
}
答案 2 :(得分:0)
dataGridView3.Rows.Cast<DataGridViewRow>()
.Select(r => r.Cells[1].Value.ToString()).ToList();
只需投射行,选择您需要的列索引或名称的单元格,无论如何都可以调整它