본문 바로가기
코딩

[Visual Studio C#] "Object reference not set to an instance of an object"Exception 해결하기

by 테크쟁이 2023. 4. 10.
반응형

TextChanged event를 등록 후, Text Box를 사용하려고 하면, 아래와 같은 exception이 발생한다.

"Object reference not set to an instance of  an object"

 

디버깅을 해보니, 초기화 될 때, TextChanged event가 호출되는데, Text Box가 아직 객체화가 되지 않아서 발생한 것이었다.

그래서 아래와 같이, null을 체크하는 부분을 추가하여 해결하였다.

- "if(tboxResultBit != null)" 참고

private void tboxResult_TextChanged(object sender, TextChangedEventArgs e)
{
    try
    {
        if(tboxResultBit != null)   // nul check 없으면 exception 발생
            tboxResultBit.Text = Convert.ToString(int.Parse(tboxResult.Text), 2);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

 

반응형