日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

DataGridView自定義單元格表示值、Error圖標顯示的方法介紹_C#教程

作者:.NET開發菜鳥 ? 更新時間: 2022-04-30 編程語言

自定義單元格表示值

通過CellFormatting事件,可以自定義單元格的表示值。(比如:值為Error的時候,單元格被設定為紅色)

示例:

private void dgv_Users_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            try
            {
                if (e == null || e.Value == null || !(sender is DataGridView))
                    return;
                DataGridView dgv = sender as DataGridView;
                if (dgv.Columns[e.ColumnIndex].Name=="Sex")
                {
                    string value = e.Value.ToString();
                    if (value.Equals("女"))
                    {
                        e.Value = "Woman";
                        e.FormattingApplied = true;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
            }
        }

Error圖標顯示

為了提醒用戶注意,DataGridView可以使用Error圖標來突出顯示。

Error圖標可以在單元格和行頭內表示,但不能在列頭上顯示。

1、ErrorText屬性

當設定單元格/行的ErrorText屬性的內容后,單元格/行的Error圖標就會被表示出來。另外,只有在DataGridView.ShowCellErrors=True時,Error圖標才能顯示。(默認屬性為True)

設定(0,0)的單元格表示Error圖標

this.dgv_Users[0, 0].ErrorText = "只能輸入男或女";

設定第4行的行頭顯示Error圖標

this.dgv_Users.Rows[3].ErrorText = "不能輸入負數";

2、CellErrorTextNeeded、RowErrorTextNeeded事件

即時輸入時的Error圖標的表示,可以使用CellErrorTextNeeded事件。同時,在大量的數據處理時,需要進行多處的內容檢查并顯示Error圖標的應用中,遍歷單元格設定ErrorText的方法是效率低下的,應該使用CellErrorTextNeeded事件。行的Error圖標的設定則應該使用RowErrorTextNeeded事件。但是,需要注意的是當DataSource屬性設定了VirtualMode=True時,上述事件則不會被觸發。

CellErrorTextNeeded、RowErrorTextNeeded事件一般在需要保存數據時使用,保存數據之前先判斷單元格輸入的值是否合法,如果不合法,則在不合法的單元格或行顯示Error圖標。相當于做了一個客戶端的驗證。

private void dgv_Users_CellErrorTextNeeded(object sender, DataGridViewCellErrorTextNeededEventArgs e)
{
            DataGridView dgv=sender as DataGridView;

            if (dgv.Columns[e.ColumnIndex].Name.Equals("Sex"))
            {
                string value = dgv[e.ColumnIndex, e.RowIndex].Value.ToString();
                if (!value.Equals("男") && !value.Equals("女"))
                {
                    e.ErrorText = "只能輸入男或女";
                }
            }
}
private void dgv_Users_RowErrorTextNeeded(object sender, DataGridViewRowErrorTextNeededEventArgs e)
{
            DataGridView dgv = sender as DataGridView;
            if (dgv["UserName", e.RowIndex].Value == DBNull.Value && dgv["Password", e.RowIndex].Value == DBNull.Value)
            {
                e.ErrorText = "UserName和Password列必須輸入值";
            }
}

原文鏈接:https://www.cnblogs.com/dotnet261010/p/6819062.html

欄目分類
最近更新