private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {int index = this.dataGridView1.CurrentCell.RowIndex;    //取出选择的单元格的行索引
            int col = this.dataGridView1.CurrentCell.ColumnIndex;//取出选择的单元格的列索引
            if (((col == 3) || (col == 1) || (col == 2)) && (this.dataGridView1.Rows[index].Cells    [col].Value.ToString().Length == 0))
            {
                MessageBox.Show("输入错误");
                e.Cancel = true;
            }
                      else if((col==4)&&(this.dataGridView1.Rows[index].Cells[col].Value.ToString().Length != 0))
            {
                float dou;
                if (Single.TryParse(this.dataGridView1.Rows[index].Cells[col].Value.ToString(), out dou))                  e.Cancel=false;
                else
                {
                    MessageBox.Show("价格输入错误");
                    e.Cancel = true;
                }
            }
            else
            { e.Cancel = false; }        }就是想让索引为1.2.3的列不能空,索引为4的列必须为float型数据或空,这样有错误吗,实际操作是不对,我找不到原因,
索引1.2.3的列我编辑为空白的时候,第一次该单元失去焦点不会验证错误,重新获得再失去焦点,则报错,但是这个时候无论输什么都是报错索引为4的,如果输入非float数据,则首先由ado.net跳出错误对话框,

解决方案 »

  1.   

    private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) 
            { 
                double d= 0.0; 
                dataGridView1.Rows[e.RowIndex].ErrorText = string.Empty; 
                if(dataGridView1.Columns[e.ColumnIndex].DataPropertyName == "") 
                { 
                    if(!double.TryParse(e.FormattedValue.ToString(),out d) ) 
                    { 
                        dataGridView1.Rows[e.RowIndex].ErrorText = "数量输入有误!"; 
                        e.Cancel = true; 
                    } 
                } 
            } 
      

  2.   

    谢谢高人,主要问题是出在如下处:
     if (e.FormattedValue.ToString().Length == 0)//这句不能用以下代替
     if (this.dataGridView1.Rows[index].Cells[col].Value.ToString().Length==0)
    或者这样也不行:
    if (this.dataGridView1.Rows[index].Cells[col].formattedValue.ToString().Length==0)但我感觉应该是一样的,不知道是为什么,能解答吗??谢谢
      

  3.   

    good good study ,day day up