2017-05-11 3 views
-1

양식에 DataGridView의 빈 행을 누를 때마다 프로그램이 중지됩니다. 이 오류는 말한다 :DataGridview에서 InvalidCastException 처리되지 않았습니다.

private void dataGridView1_Click(object sender, EventArgs e) 
{ 
    id = Convert.ToInt32(dataGridView1.SelectedCells[0].Value); //This is the line with the error 
    textBox1.Text = dataGridView1.SelectedCells[1].Value.ToString(); 
    textBox2.Text = dataGridView1.SelectedCells[2].Value.ToString(); 
    textBox3.Text = dataGridView1.SelectedCells[3].Value.ToString(); 
    textBox4.Text = dataGridView1.SelectedCells[4].Value.ToString(); 
} 
+0

당신이있는 DataGridView를 클릭 할 때 응용 프로그램을 시작하거나 할 때 발생하는 문제는? 셀이 숫자가 아니거나, 널이거나, 선택된 행이 없기 때문입니다. null 일 때 대소 문자를 처리하기 위해 "int? id"를 시도 할 수 있습니다. 폼을 생성하는 동안 메서드에 들어갈 수 있으며 datatGridView1.Rows.Count <= 0; – jdweng

+0

'DataGridView'의 빈 행을 클릭 할 때마다 오류가 나타납니다. 아마도 마지막 행이 있습니다. 'id' 변수는'int' 자료형을 가지고 있습니다. @jdweng – StarBoy

+0

변수 형 int를 만들 수 있다고 말했습니까? 그래서 Convert.ToInt32는 오류를주지 않거나 doe dataGridView1.SelectedCells == null 또는 dataGridView1.SelectedCells [0] == null – jdweng

답변

0

당신이 말한 것 같이

program stop whenever i press the blank row

다음 당신이있어

id = Convert.ToInt32(dataGridView1.SelectedCells[0].Value); //This is the line with the error 

Int가 값 형식이고 null이 될 수 없으며, 때문에 항상 실패 할 때 ' 비어있는 행이 있는데이 셀의 값은 대체로 null입니다. 이 같은

시도 뭔가 : 셀 값이있는 경우

try 
{ 
    id = Convert.ToInt32(dataGridView1.SelectedCells[0].Value); //This is the line with the error 
    textBox1.Text = dataGridView1.SelectedCells[1].Value.ToString(); 
    textBox2.Text = dataGridView1.SelectedCells[2].Value.ToString(); 
    textBox3.Text = dataGridView1.SelectedCells[3].Value.ToString(); 
    textBox4.Text = dataGridView1.SelectedCells[4].Value.ToString(); 
} 
catch(InvalidCastException exception) 
{ 
    // not much to do with it, you can display assign empty valuest to your text boxes or notify user that there's nothing to select 
} 

대체 apporach는 확인 할 수있다.

if(string.IsNullOrWhiteSpace(dataGridView1.SelectedCells[0].Value)) 
{ 
    return; 
} 

id = Convert.ToInt32(dataGridView1.SelectedCells[0].Value); 
//Assign values to textboxes 

그리고 또 다른 가능성도있다 :

int id; 
if(int.TryParse(dataGridView1.SelectedCells[0].Value.ToString(), out id)) 
{ 
    //Assign values to textboxes 
} 
+0

첫 번째 해결책은 오류가 있습니다 :' 'e'라는 로컬 변수는 이미 '부모 또는 현재'범위에서 사용 된 'e'와는 다른 의미를 부여하기 때문에이 범위에서 선언 할 수 없습니다 다른 것을 나타 내기 위해 ' – StarBoy

+0

맞습니다. EventArgs 매개 변수는'e '로 선언됩니다. 나는 이것을 갱신 할 것이다. – yoger

+0

이고 두 번째 여전히 InvalidCastException이 처리되지 않았습니다. 여전히 3 호가 2 개의 오류를 가지고 있지만 그것을 고치려고 노력하고 있습니다. 잘 말하면 좋지 않습니다. @yoger – StarBoy

0

첫번째 그리드 셀의 데이터 유형은 무엇입니까 :

InvalidCastException was unhandled.

이 오류가 일어나고 코드의 일부이다?

변환하려는 변수가 숫자가 아니거나 특수 문자 데이터 유형이므로 오류의 원인이됩니다. 숫자가 아닌 숫자 또는 숫자가 아닌 숫자와 숫자 데이터를 함께 사용하려면 convert.toString() 메서드를 사용하는 것이 좋습니다.

+0

im을'id'에 대해'int' 데이터 유형을 사용하여 테스트합니다. 프로그램이'id' 변수에 넘기는 값은 자동 데이터베이스입니다 ... 내 데이터베이스의 넘버링 시스템을 위해 그것을 사용합니다. @mBangali – StarBoy

관련 문제