[英]DataGridView How to check if a cell is empty?
我正在开发一个包含 DataGridView 和表单的程序,我正在将数据从 XML 文件导入到这个 DataGridView。 在此 DataGridView 中,我可以添加、编辑和删除此数据,并在单击按钮时将此更改保存到 XML 文件中。 (有两列。)我的问题是我需要检查单击按钮时是否有任何单元格为空,在这种情况下,显示一个 MessageBox 指示这一点,并且不要让我保存此更改。
我试过 for 循环等等,但找不到任何有用的东西。 希望有人能帮助我! 谢谢
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace Sullair
{
public partial class IPs : Form
{
public IPs()
{
InitializeComponent();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
}
private void IPs_Load(object sender, EventArgs e)
{
try
{
DataSet ds = new DataSet();
ds.ReadXml(@"C:\Users\Administrador\source\repos\Sullair\schema.xml");
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void Save()
{
DataTable db = (DataTable)dataGridView1.DataSource;
db.WriteXml(@"C:\Users\Administrador\source\repos\Sullair\schema.xml");
}
private void btnSave_Click(object sender, EventArgs e)
{
Save();
}
}
}
//以此为例,当有空值时显示一条消息 show (no) //如果没有空值则打开文件对话框
if (string.IsNullOrEmpty(metroGrid2.CurrentRow.Cells["FileName"].Value as string))
{
MessageBox.Show("no");
}
else
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK)
{
folder = fbd.SelectedPath;
}
}
只需对表格单元格进行嵌套循环,如下所示:
private bool AreAllCellsFilled(DataTable t)
{
if (t == null || t.Rows.Count == 0 || t.Columns.Count == 0) return true;
for (int rowIdx = 0; rowIdx < t.Rows.Count; rowIdx++)
{
for (int colIdx = 0; colIdx < t.Columns.Count; colIdx++)
{
if (t.Rows[rowIdx][colIdx] == DBNull.Value)
{
MessageBox.Show($"Cell {colIdx + 1} of row {rowIdx + 1} is empty");
return false;
}
}
}
return true;
}
foreach(DataGridViewRow row in dataGridView1.Rows)
{
foreach(DataGridViewCell cell in row.Cells)
{
if(string.IsNullOrEmpty(cell.Value as string))
{
//cell is empty
}
else
{
//cell is not empty
}
}
}
这对我有用。 检查特定单元格是否为空或为空。
if (string.IsNullOrEmpty(dataGridView_A0.Rows[0].Cells[0].Value as string))
{
MessageBox.Show("Null or Empty", "Results");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.