본문 바로가기
[2]SW Development Note/[2-1.2]C#

처리되지 않은 'System.InvalidCastException' 형식의 예외가 발생했습니다. (int)=>Convert.ToInt32

by 오늘도 빛나는 너에게 2022. 5. 6.
728x90
[bug]
string(문자열) 에서 Int(정수) 형 변환  오류.  ( 'System.InvalidCastException')

(int) HbjGridView.GetRowCellValue(HbjGridView.FocusedRowHandle, "ID"))​

 

수정 코드
Convert.ToInt32(HbjGridView.GetRowCellValue(HbjGridView.FocusedRowHandle, "ID"))
 
예제 코드
string s1 = "1234";
string s2 = "1234.65";
string s3 = null;
string s4 = "123456789123456789123456789123456789123456789";

int result;
bool success;

Int32.parse(문자열)

//Int32.Parse (string s) 메서드는 string 숫자 표현을 해당하는 32비트 부호 있는 정수로 변환
//참조인 s 경우 null throw ArgumentNullException .
//값 s 이 아닌 경우 integer throw FormatException. 
Int32.parse(문자열)
result = Int32.Parse(s1); //-- 1234
result = Int32.Parse(s2); //-- FormatException
result = Int32.Parse(s3); //-- ArgumentNullException
result = Int32.Parse(s4); //-- OverflowException

Convert.ToInt32(문자열)
//알 수없는 유형의 객체를 변환. 
//명시 적 및 암시 적 변환 또는 IConvertible 구현이 정의 된 경우 이를 사용.
//Convert.ToInt32(string s)메서드는 지정된 string 32비트 부호 있는 표현을 변환. 
//s3가  null경우 throw하지 않고 0을 반환 . 
Convert.ToInt32(문자열)
result = Convert.ToInt32(s1); //-- 1234
result = Convert.ToInt32(s2); //-- FormatException
result = Convert.ToInt32(s3); //-- 0
result = Convert.ToInt32(s4); //-- OverflowException

Int32.TryParse(문자열, 정수 출력)

//Int32.Parse(string, out int)메서드는 변수에 string 해당하는 32비트 부호 있는 정수 의 
//지정된 표현을 변환하고 성공적으로 구문 분석되면 반환하고 그렇지 않으면 반환
//S 가 참조 인 경우 throw하지 않고 반환됩니다 .   
 //Int32.TryParsryParse 항상 자체적으로 예외를 처리.
// Int32.TryParse는 bool 형식이기 때문에 형반환 검증으로 사용하기에 최적.
Int32.TryParse(문자열, 정수 출력)
success = Int32.TryParse(s1, out result); //-- success => true; result => 1234
success = Int32.TryParse(s2, out result); //-- success => false; result => 0
success = Int32.TryParse(s3, out result); //-- success => false; result => 0
success = Int32.TryParse(s4, out result); //-- success => false; result => 0
728x90

댓글