+ -
当前位置:首页 → 问答吧 → dataGridView中两列的值比较大小

dataGridView中两列的值比较大小

时间:2011-12-26

来源:互联网

 
   
  for (int i = 0; i < dataGridView1.Rows.Count; i++)
  {

  if (Convert.ToInt32(dataGridView1.Rows[i].Cells[4].Value.ToString()) > Convert.ToInt32(dataGridView1.Rows[i].Cells[3].Value.ToString()))
  {
  dataGridView1.Rows[i].ErrorText = "实际入库量不能大于订购量";
  MessageBox.Show("实际入库量不能大于订购量");
  e.Cancel = true;
  }
  }

我想比较3、4列两个单元的值,但这样写不行,说什么对象没初始化,请问该怎么改或者有什么更好的方法实现,O(∩_∩)O谢谢!!
 

作者: abcwlm   发布时间: 2011-12-26

string s1 = dataGridView1.Rows[i].Cells[4].Value.ToString();
string s2 = dataGridView1.Rows[i].Cells[3].Value.ToString();
如果是数值型的,最好转成数值再比较,比较真实,字符串的大小比较有时候可能结果不是
你想要的,
decimal d1 = (decimal)dataGridView1.Rows[i].Cells[4].Value.ToString();
decimal d2 = (decimal)dataGridView1.Rows[i].Cells[3].Value.ToString();

对象没有初始化,有可能是在你写的代码的事件加载时,dataGridView1尚没有数据.

作者: ccy_qty   发布时间: 2011-12-26

引用 1 楼 ccy_qty 的回复:
string s1 = dataGridView1.Rows[i].Cells[4].Value.ToString();
string s2 = dataGridView1.Rows[i].Cells[3].Value.ToString();
如果是数值型的,最好转成数值再比较,比较真实,字符串的大小比较有时候可能结果不是
你想要的,
decimal d1 = (decimal)dataG……


转换为数字类型是肯定的。
另外要注意所在的事件。

作者: avon520   发布时间: 2011-12-26

在转换前你得确认 获取的值是不是为空啊,然后再进行转换,不然会出错

下面这样就是转换失败的时候值为0
C# code

double d1=0.0;
double.TryParse(dataGridView1.Rows[i].Cells[4].Value.ToString(),out d1);

作者: zhangbin1988   发布时间: 2011-12-26