C# 如何在DataGridView中使用验证

C# 如何在DataGridView中使用验证,c#,datagridview,C#,Datagridview,在我的程序中,当我单击DataGridView中的某一行时,如果该行包含“\”,它应该会弹出一条错误消息,指出“\在名称或路径中是不允许的”。我不知道怎么做 代码如下: namespace OVF_ImportExport { public partial class Form1 : Form { string sName = ""; string sPath = ""; public Form1()

在我的程序中,当我单击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();
        }
尝试使用以下方法:

// Attach DataGridView events to the corresponding event handlers.      
 this.dataGridView1.CellValidating += new DataGridViewCellValidatingEventHandler(dataGridView1_CellValidating);
用于上述事件处理程序的方法:

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

为什么您只想在单击行时标记此错误?如果行中不允许某些数据,那么为什么不在数据绑定之前清除这些数据呢?