如何使用C#检查datagridview中的空单元格和空单元格
我试图检查datagridview单元格的空值和空值…但我不能正确…
for (int i = 0; i < dataGridView1.Rows.Count; i++) { if ((String)dataGridView1.Rows[i].Cells[3].Value == String.Empty) { MessageBox.Show(" cell is empty"); return; } if ((String)dataGridView1.Rows[i].Cells[3].Value == "") { MessageBox.Show("cell in empty"); return ; } }
我甚至试过这个代码
if (String.IsNullOrEmpty(dataGridView1.Rows[i].Cells[3].Value)) { MessageBox.Show("cell is empty"); return; }
谁能帮我这个…
我会尝试这样的:
foreach (DataGridViewRow rw in this.dataGridView1.Rows) { for (int i = 0; i < rw.Cells.Count; i++) { if (rw.Cells[i].Value == null || rw.Cells[i].Value == DBNull.Value || String.IsNullOrWhiteSpace(rw.Cells[i].Value.ToString()) { // here is your message box... } } }
if (!GridView1.Rows[GridView1.CurrentCell.RowIndex].IsNewRow) { foreach (DataGridViewCell cell in GridView1.Rows[GridView1.CurrentCell.RowIndex].Cells) { //here you must test for all and then return only if it is false if (cell.Value == System.DBNull.Value) { return false; } } }
if (String.IsNullOrEmpty(dataGridView1.Rows[i].Cells[3].Value as String)) { MessageBox.Show("cell is empty"); return; }
添加as String
,它适用于我。
我想你应该先检查一下null
Convert.IsDBNull(dataGridView1.Rows[j].Cells[1].FormattedValue)
我想你应该用这个:
for (int i = 0; i < dataGridView1.RowCount; i++) { for (int j = 0; j < dataGridView1.ColumnCount; j++) { if (dataGridView1.Rows[i].Cells[j].Value == DBNull.Value) { dataGridView1.Rows[i].Cells[j].Value = "null"; } } } dataGridView1.Update();
for (int i = 0; i < GV1.Rows.Count; i++) { if ((String)GV1.Rows[i].Cells[4].Value == null) { MessageBox.Show(" cell is empty"); return; } }
它工作正常。
试试这个 :
foreach (DataGridViewRow row in dataGridView.Rows) { IEnumerable cellsWithValusInRows = from DataGridViewCell cell in row.Cells where string.IsNullOrEmpty((string)cell.Value) select cell; if (cellsWithValusInRows != null && cellsWithValusInRows.Any()) { //Then cells with null or empty values where found } }
然后检查集合是否为null或具有元素。
我希望这可以帮到你。
适合我的作品:
for (int i = dataGridView1.Rows.Count - 1; i >= 0; i--) { DataGridViewRow dataGridViewRow = dataGridView1.Rows[i]; foreach (DataGridViewCell cell in dataGridViewRow.Cells) { string val = cell.Value as string; if (string.IsNullOrEmpty(val)) { if (string.IsNullOrEmpty(dataGridView1.Rows[i].Cells[3].Value as string)) // If you want to check more then just one cell you could also add "&& (string.IsNullOrEmpty(dataGridView1.Rows[i].Cells[ANY NUMBER].Value as string) { MessageBox.Show(" cell is empty"); return; /* or to delete replace with: dataGridView1.Rows.Remove(dataGridViewRow); break; */ } } } }