2016-06-21 1 views
2

저는 ASP.NET과 C#에서 초보자입니다. 위 문자로 시작하는 gridview의 모든 셀 값에 배경색을 추가하고 싶습니다. 여기 내 소스 코드 :gridview의 모든 셀 값에 배경색을 추가 하시길 바랍니다.

protected void OnRowDataBound(object sender, GridViewRowEventArgs e) 
{ 
      if (e.Row.RowType == DataControlRowType.DataRow) 
      { 
       TableCell cell = e.Row.Cells[2]; 
       string entity = cell.Text.ToString(); 
       if (entity[0] >= 'A' && entity[0] <= 'Z') 
       { 
        cell.BackColor = Color.Yellow; 
       } 
      } 
} 

하지만이 오류가있어 :

Index was outside the bounds of the array. 

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.IndexOutOfRangeException: Index was outside the bounds of the array. 

Source Error: 


Line 85:     TableCell cell = e.Row.Cells[1]; 
Line 86:     string entity = cell.Text.ToString(); 
Line 87:     if (entity[0] >= 'A' && entity[0] <= 'Z') 
Line 88:     { 
Line 89:     cell.BackColor = Color.Yellow; 

Source File: c:\Users\Eric\Default.aspx.cs Line: 87 

날이 오류를 해결하기 위해 도와주세요

이 문제는 이것으로 모든

+0

'char'는'IsUpper' 메소드를 가지고 있습니다. 당신은'char.IsUpper (entity [0])'를 사용할 수 있습니다. 단지'entity'가 null이 아니고 적어도 하나의 문자를 가지고 있는지 확인하십시오. –

답변

1

에게 감사를 줄 :

if (entity[0]... 

셀 값이 null이거나 비어 있으면 엔터티에 요소가 없습니다. 이렇게하면 범위를 벗어나는 예외가 발생합니다.

먼저 배열에 요소가 있는지 확인하여 문제를 해결할 수 있습니다.

if (!string.IsNullOrEmpty(entity) && entity[0] >= 'A' && entity[0] <= 'Z') 
{ 
    //your code here 
} 

편지가 실제로

+0

여기 엔 대괄호가 필요하지 않습니다. (엔티티 [0]> = 'A'&& 엔티티 [0] <= 'Z') –

+0

위의 문자로 시작하는 셀에는 코드가 추가되지 않습니다! – mynhylisti

+1

@AlexOvechkin 당신이 옳습니다. –

0

cell.Text.ToString() 반환이 같은 빈 문자열이있는 경우에만 대문자를 확인합니다 이런 식으로 ""를. 문제는 그 셀에서 아무런 가치가 없다는 것입니다. 따라서 string의 첫 번째 위치에 액세스하려고하면 예외가 발생합니다. 87 행에서 예외 메시지가 명확합니다.

해결 방법은 실제로 null 또는 비어 있는지 확인하는 것입니다.

관련 문제