private void dataGridView1_CellPainting_1(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex == -1)
                return;            DataGridViewRow dgr = dataGridView1.Rows[e.RowIndex];
            try
            {
                if (int.Parse(dataGridView1.Rows[e.RowIndex].Cells["id"].Value.ToString()) > 10)
                {                    e.CellStyle.ForeColor = Color.Red;
                }            }
            catch { }       
        }    //  如上,如果我不try,catch一下的话,字体颜色是改变了,但是只是晃的一下就没了,接着就是一把好大好大的红
    // 叉叉!完了就报一个错~ 
     
   // 疑问1:有没有办法在不捕捉异常的情况下改一下上面的代码让它不报错了?
   // 疑问2:如果我不改代码,就跟上面一样搞,虽然异常没有报了,大红叉也没有了,程序会不会一直在这里吃内存了?
   //           如果没有吃内存的话,是不是这样就行得通了?

解决方案 »

  1.   

    int i=0;
    int.TryParse(dataGridView1.Rows[e.RowIndex].Cells["id"].Value,out i);
    if(i>10)
    {}
      

  2.   

    内存不会泄露,但是效率不如TryParse来的高,Parse内部也是调用的tryParse,然后根据情况决定抛不抛异常
      

  3.   

    放到CellFormating里做,个人不推荐操作CellPainting事件,除非你想自己重绘Cell
    另外int.Parse是有异常风险的,建议用TryParse. private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
            {
                DataGridViewRow dgr = dataGridView1.Rows[e.RowIndex];            int id;
                if (e.Value != null && int.TryParse(e.Value.ToString(), out id) && id > 10)
                {
                    e.CellStyle.ForeColor = Color.Red;
                }   
            }