2015-07-20 57 views
3

在我的程序中,當我點擊DataGridView中的一個特定行時,如果該行包含"\"它應該彈出一條錯誤消息"\ is not allowed in name or in path"。我不知道該怎麼做。如何在DataGridView中使用驗證

下面是代碼:

namespace OVF_ImportExport 
{ 
    public partial class Form1 : Form 
    { 

     string sName = ""; 
     string sPath = ""; 
       public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) 
     { 

      foreach (DataGridViewRow row in dataGridView1.SelectedRows) 
      { 
       sName = row.Cells[0].Value.ToString(); 
       sPath = row.Cells[1].Value.ToString(); 

      } 
     } 

     private void BtnCreate_Click(object sender, EventArgs e) 
     { 
      richTextBox1.Text = ""; 
      StreamWriter file = new StreamWriter("Export.bat"); 
      file.WriteLine("c: "); 
      file.WriteLine("cd \\"); 
      file.WriteLine("cd Program Files "); 
      file.WriteLine("cd VMware"); 
      file.WriteLine("cd VMware OVF Tool"); 

      foreach (DataGridViewRow row in dataGridView1.SelectedRows) 
      { 
       sName = row.Cells[0].Value.ToString(); 
       sName = sName.Trim(); 
       sPath = row.Cells[1].Value.ToString(); 

       file.WriteLine("start ovftool.exe --powerOffSource vi://" + TxtUsername.Text + ":" + TxtPassword.Text + "@" 
        + TxtIP.Text + sPath + " " + "\"" + TxtBrowsepath.Text + "\\" + sName + "\\" + sName + ".ovf" + "\"" + Environment.NewLine); 



      } 
      file.WriteLine("pause"); 
      MessageBox.Show("Batch File Created","Batch File"); 
      file.Close(); 
     } 
+0

只將此錯誤上點擊:

// Attach DataGridView events to the corresponding event handlers. this.dataGridView1.CellValidating += new DataGridViewCellValidatingEventHandler(dataGridView1_CellValidating); 

方法上面的事件處理程序該排?如果行中不允許某些數據,那麼爲什麼不在數據綁定之前清除它的這些數據呢? – sr28

回答

2

嘗試使用這樣的:你爲什麼要

private void dataGridView1_CellValidating(object sender, 
     DataGridViewCellValidatingEventArgs e) 
    { 
     // Validate the CompanyName entry by disallowing empty strings. 
     if (dataGridView1.Columns[e.ColumnIndex].Name == "CompanyName") 
     { 
      if (String.IsNullOrEmpty(e.FormattedValue.ToString())) 
      { 
       dataGridView1.Rows[e.RowIndex].ErrorText = 
        "Company Name must not be empty"; 
       e.Cancel = true; 
      } 
     } 
    }