[C#.NET][Winform][ADO.NET] 依條件設定 DataGridView.CurrentCell 焦點

目前有一個需求,使用者對DataGridView中的儲存格輸入字串,若字串條件不符合規則,輸入焦點需停在該儲存格,其他儲存格不得輸入,待該儲存格符合條件後,焦點方能離開該儲存格。

要達到這功能主要需要兩個事件CellEndEdit、SelectionChanged

 

1.由CellEndEdit事件判斷儲存格內的資料,是否吻合我們所需要的條件,若條件不符合則用_PreviousViewCell變數記錄錯誤的儲存格。

2.使用SelectionChanged事件,不論滑鼠鍵盤點到哪裡,DataGridView將回到錯誤的儲存格編輯。

DataGridViewCell _PreviousViewCell = null;
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    DataGridView currentView = (DataGridView)sender;
    if (currentView == null)
        return;
    if (e.RowIndex == -1)
        return; 

    string value = "";
    float data = 0;
    bool IsError = false;
    //1.判斷儲存格內的條件
    if (currentView.CurrentCell.Value == null)
    {
        currentView.CurrentCell.ErrorText = "不得為空";
        IsError = true;
    }
    else
    {
        value = currentView.CurrentCell.Value.ToString();
        if (value == "")
        {
            currentView.CurrentCell.ErrorText = "不得為空";
            IsError = true;
        }
        else
        {
            currentView.CurrentCell.ToolTipText = data.ToString();
            currentView.CurrentCell.ErrorText = "";
            IsError = false;
        }
    }
    //記錄錯誤的儲存格
    if (IsError == true)
    {
        this._PreviousViewCell = currentView.CurrentCell;
        dataGridView1.CurrentCell = this._PreviousViewCell;
    }
    else
    {
        this._PreviousViewCell = null;
    }
}

 

 

private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
    if (_PreviousViewCell == null)
    {
        return;
    }
    try
    {
        this.dataGridView1.CurrentCell = this._PreviousViewCell;
        this.dataGridView1.CurrentCell.Selected = true;
        this.dataGridView1.BeginEdit(true);
    }
    catch (Exception)
    { 

    }
}

 

看似簡單的一個功能,卻困擾了我很久,我今天也花了一個下午才將此功能完成。

到目前為止功能已經完成了,但我在測試時點了DataGridView的排序,上面功能就失效了,所以我將再利用CellClick來啟/停排序功能

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (this.dataGridView1.IsCurrentCellInEditMode)
    {
        //禁止排序
        for (int i = 0; i < this.dataGridView1.Columns.Count; i++)
        {
            this.dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
        }
    }
    else
    {
        //啟用排序
        for (int i = 0; i < this.dataGridView1.Columns.Count; i++)
        {
            this.dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.Automatic;
        }
    }
}
 

範例下載:DataGridView_CellFocus.zip

本文转自http://www.dotblogs.com.tw/yc421206/archive/2010/11/10/19345.aspx

posted @ 2014-02-10 14:46  Net-Spider  阅读(676)  评论(0)    收藏  举报