[英]DataGridView cell is null on CellLeave
當我離開單元格時,我試圖對單元格的內容進行一些文本處理。 我有以下代碼,但是當我在單元格中輸入任何文本然后離開時,我得到以下異常。
An unhandled exception of type 'System.NullReferenceException' occurred in Program.exe
Additional information: Object reference not set to an instance of an object.
如果我在上面斷開和鼠標懸停.value
它確實為空,但我已將數據輸入到單元格中! 什么給出了什么?
private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 3)
{
string entry = "";
MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
MakeTextFeet(entry);
}
if (e.ColumnIndex == 4)
{
string entry = dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString();
MakeTextFeet(entry);
}
}
觸發DataGridView CellLeave事件時,單元格的值處於瞬態狀態。 這是因為DataGridView可能綁定到數據源,並且不會提交更改。
您最好的選擇是使用CellValueChanged事件。
添加一些檢查:
DataGridViewCell MyCell = dataGridView1[e.ColumnIndex, e.RowIndex];
if (MyCell != null)
{
if (MyCell.Value != null)
{
}
}
我想你想要處理CellEndEdit而不是CellLeave。
在CellLeave上,編輯的單元格的Value屬性仍然保持不變(即,通過斷開和檢查Value觀察到的空單元格為null)。 在CellEndEdit上,已設置其新值。
嘗試這樣的事情,其中我試圖通常堅持你的原始代碼:
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
DataGridViewCell cell = dataGridView1[e.ColumnIndex, e.RowIndex];
if (e.ColumnIndex == 3 || e.ColumnIndex == 4)
{
string entry = "";
if (cell.Value != null)
{
entry = cell.Value.ToString();
}
MessageBox.Show(entry);
MakeTextFeet(entry);
}
}
我想你要留下一個空白區域並試圖處理它的價值。
當您將保留以下代碼的空白單元格值時:
string entry = dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString();
字符串條目中的值將是空格(entry =“”),當您通過將其傳遞給另一個函數[MakeTextFeet(entry);]進一步處理此值時,它會給您錯誤。
從我的角度來看這個問題的解決方案是>>>
將每行代碼放在上面的方法中,MakeTextFeet(Entry)也在try塊中。
當你寫catch塊時,將該塊留空。 例如。
try
{
.
.
.
}
catch(Exception)
{
}
通過這件事你的異常自然會被抓住,但由於它的不可忽視,它不會告訴你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.