2016-03-22 23 views
-3

有两列gridview,一个有值,另一个会每个月都有。我想使用条件运算符(>或<)来比较两列。 我使用了下面的代码,但它不起作用。如何在c的gridview列中使用条件运算符#

protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     string Threshold = e.Row.Cells[3].Text; 
     int result = int.Parse(Threshold.Replace("%", "")); 

     int ThreCol; 
     int ResCol; 

     ThreCol = int.Parse(e.Row.Cells[3].Text); 
     ResCol = int.Parse(e.Row.Cells[4].Text); 

      if (e.Row.Cells[4].Text == result.ToString().Trim()) 
      { 
       e.Row.Cells[4].BackColor = Color.MediumSeaGreen; 
      } 
       if (ResCol > ThreCol) 
      { 
       e.Row.Cells[4].BackColor = Color.Yellow; 
      } 
      else 
      { 
       e.Row.Cells[4].BackColor = Color.LightCoral; 
      } 
     } 
    } 

错误

输入字符串的不正确的格式。

screenshot of the error

+5

看看错误发生的路线。然后再次读取错误信息:'输入字符串格式不正确。您试图将字符串解析为整数,但字符串无效。 – Rob

+6

解决方案是使用调试器,找出哪条线路坏了,查看字符串,并找出字符串为什么不是数字,或者为什么你认为它是一个数字。 SO不是调试服务。 – Rob

+0

请显示您的Gridview – fubo

回答

0

这个错误是因为你想Parse的字符串(如罗布在评论中提到),这是不int。您应该使用Int32.TryParse来处理这些类型的情况:

//don't need to parse "result" as "int" 
int result = e.Row.Cells[3].Text.Replace("%", ""); 

//initiate with default values 
int ThreCol = 0; 
int ResCol = 0; 

//try parsing 
Int32.TryParse(e.Row.Cells[3].Text, out ThreCol); 
Int32.TryParse(e.Row.Cells[4].Text, out ResCol); 

PS:我使用默认值0因为我不知道上下文),所以您的病情if (ResCol > ThreCol)将失败两者都没有任何价值。

+0

谢谢Shaharyar。 – Hadia

1

可能occure,要么e.Row.Cells[3].Text;e.Row.Cells[4].Text不能被解析成int(例如,在空字符串的情况下)。 尝试使用int.TryParse

protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e){ 
    if (e.Row.RowType == DataControlRowType.DataRow) { 
    string Threshold = e.Row.Cells[3].Text.Replace("%", "").Trim(); 

    // Exact match 
    if (e.Row.Cells[4].Text == Threshold) 
     e.Row.Cells[4].BackColor = Color.MediumSeaGreen; 
    else { 
     // no match: either threshold is exceeded or values are incomparable 
     int ThreCol; 
     int ResCol; 

     // Both values are integers and ResCol > ThreCol 
     if (int.TryParse(e.Row.Cells[3].Text.Replace("%", ""), out ThreCol) && 
      int.TryParse(e.Row.Cells[4].Text.Replace("%", ""), out ResCol) && 
      ResCol > ThreCol) 
     e.Row.Cells[4].BackColor = Color.Yellow; 
     else 
     e.Row.Cells[4].BackColor = Color.LightCoral; 
    } 
    ... 

请注意e.Row.Cells[3].Text.Replace("%", "") - 你必须在第二种情况下删除%为好。

+0

这个错误也可能是由单元格内的嵌套控制引起的[e.Row.Cells [1] .Controls [0]' – fubo

+0

@fubo:这是一种可能性,但是由于它是''在'int.Parse e.Row.Cells [3] .Text);'我猜99.9%的机会是'e.Row.Cells [3] .Text'不能被解析为'int' –

+0

非常感谢#Dmitry Bychenko的工作。 – Hadia