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

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

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

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

自定義單元格表示值

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

示例:

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圖標(biāo)顯示

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

Error圖標(biāo)可以在單元格和行頭內(nèi)表示,但不能在列頭上顯示。

1、ErrorText屬性

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

設(shè)定(0,0)的單元格表示Error圖標(biāo)

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

設(shè)定第4行的行頭顯示Error圖標(biāo)

this.dgv_Users.Rows[3].ErrorText = "不能輸入負(fù)數(shù)";

2、CellErrorTextNeeded、RowErrorTextNeeded事件

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

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

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

欄目分類
最近更新