2017-05-21 3 views
-1

이것은 아마도 dublicate로 표시되거나 닫히지 만 묻지해야합니다. 여기 불법은 무엇입니까? 개체 참조가 개체의 인스턴스로 설정되지 않았지만 불법적 인 것으로 표시되지 않습니다.

private void btnFind_Click(object sender, EventArgs e) 
{ 
    connection.Open(); 
    OleDbCommand command1 = new OleDbCommand(); 
    command1.Connection = connection; 
    command1.CommandText = "select antonym from antonymsdb where word ='" + txtWord.Text + "'"; 
    string antonymdoc = command1.ExecuteScalar().ToString(); 
    lblAntonym.Text = antonymdoc; 

    OleDbCommand command2 = new OleDbCommand(); 
    command2.Connection = connection; 
    command2.CommandText = "select word from antonymsdb where antonym = '" + txtWord.Text + "'"; 
    string antonymdocx = command2.ExecuteScalar().ToString(); 
    lblAntonym.Text = antonymdocx; 
    connection.Close(); 
} 

난, 그냥 다른 열을 모두 열 단어반의어를 읽고 같은 행의 말씀을 반환하기 위해 노력하고있어. 쿼리가 다음 ExecuteScalar 반환는 null 레코드를 반환하지 않는 경우

string antonymdoc = command1.ExecuteScalar().ToString(); 

:

+0

에 대한 속기는

var output = command1.ExecuteScalar(); string antonymdoc = output != null ? output.ToString() : string.Empty; 

속기 당신이

string antonymdoc = command1.ExecuteScalar()?.ToString() ?? string.Empty; 

할 수없는 결과가 없을 때 빈 문자열을 얻고 싶었다 경우

'그것 오류 표시'오류 텍스트 란 무엇입니까? – Neolisk

+1

** 디버거 사용 **. –

+0

왜 이것이 중복인지 잘 모르겠습니다. 질문은 NullReferenceException이 무엇인지가 아닙니다. 문제는이 코드가 왜 던지고 있는지입니다. 앞서 언급했듯이 이것은 디버거에서보다 쉽게 ​​발견 할 수있는 종류의 것입니다. 프로덕션 코드가 아니라면 예외를 던지는 방법 만 있으면됩니다. 그런 다음 코드를 읽고 "null을 찾아야합니다." –

답변

1

이 용의자는 ... 그것은 오류를 보여주는 유지하고 나는 인터넷을 검색했는데, 도움이 아무것도 찾을 수 없습니다. null에 .ToString() (으)로 전화하면 NullReferenceException이 표시됩니다.

일반적으로 결과가 반환되는지 알 수 있도록 결과가 null인지 확인합니다. 그냥

var output = command1.ExecuteScalar(); 
string antonymdoc; 
if(output!=null) 
{ 
    antonymdoc - output.ToString(); 
} 
else 
{ 
    antonymdoc = string.Empty; 
}