[英]datagridview cell click event
我有一個在數據網格視圖中單擊單元格的事件,以在消息框中顯示單擊的單元格中的數據。 我將它設置為僅適用於特定列且僅當單元格中有數據時才適用的位置
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex.Equals(3))
if (dataGridView1.CurrentCell != null && dataGridView1.CurrentCell.Value != null)
MessageBox.Show(dataGridView1.CurrentCell.Value.ToString());
}
但是,每當我單擊任何列標題時,都會出現一個空白消息框。 我不知道為什么,有什么提示嗎?
您還需要檢查單擊的單元格不是列標題單元格。 像這樣:
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex.Equals(3) && e.RowIndex != -1){
if (dataGridView1.CurrentCell != null && dataGridView1.CurrentCell.Value != null)
MessageBox.Show(dataGridView1.CurrentCell.Value.ToString());
}
檢查CurrentCell.RowIndex
是否不是標題行索引。
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1) return; //check if row index is not selected
if (dataGridView1.CurrentCell.ColumnIndex.Equals(3))
if (dataGridView1.CurrentCell != null && dataGridView1.CurrentCell.Value != null)
MessageBox.Show(dataGridView1.CurrentCell.Value.ToString());
}
接受的解決方案拋出“對象未設置為對象的實例”異常,因為在檢查變量的實際值之前必須進行空引用檢查。
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentCell == null ||
dataGridView1.CurrentCell.Value == null ||
e.RowIndex == -1) return;
if (dataGridView1.CurrentCell.ColumnIndex.Equals(3))
MessageBox.Show(dataGridView1.CurrentCell.Value.ToString());
}
試試這個
if(dataGridView1.Rows.Count > 0)
if (dataGridView1.CurrentCell.ColumnIndex == 3)
MessageBox.Show(dataGridView1.CurrentCell.Value.ToString());
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex.Equals(0))
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
enter code here
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.