2017-10-04 60 views
0

我正在開發一個包含DataGridView白皮書的程序,我正在從XML文件導入數據到這個DataGridView。 在這個DataGridView中,我可以添加,編輯和刪除這些數據,並在單擊按鈕時將這些更改保存到XML文件中。 (有兩列) 這裏我的問題是,我需要檢查單擊按鈕時是否有空單元,在這種情況下,顯示一個MessageBox指示這一點,不要讓我保存這些更改。DataGridView如何檢查單元格是否爲空?

我試過循環和更多,並找不到有用的東西。 希望有人能幫助我!由於

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(); 
    } 

} 
} 

回答

0

只是做一個嵌套循環在表格單元格,這樣的事情:

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; 
} 
0
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 
      } 
    } 
} 
0

//把這個作爲例子當出現空值顯示一條消息顯示(無) //如果沒有空值打開文件對話框

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; 




      } 
     } 
相關問題