مشاركة عبر


كيفية القيام بما يلي: تخصيص تنسيق البيانات في عنصر تحكم DataGridView Windows Forms

يوضح مثال التعليمات البرمجية التالي كيفية تنفيذ معالج حدث DataGridView.CellFormatting الذي يقوم بتغيير كيفية عرض الخلايا استناداً على الأعمدة والقيم الخاصة بها.

الخلايا في عمود Balance التي تحتوي على أرقام سالبة تعطى خلفية بلون أحمر. يمكنك أيضا تنسيق هذه الخلايا كعملة لعرض أقواس حول القيم السالبة. لمزيد من المعلومات، راجع كيفية القيام بما يلي: تنسيق البيانات في عنصر تحكم DataGridView الخاص بـ Windows Forms.

تعرض خلايا عمود Priority صوراً في مكان قيم الخلايا النصية المقابلة. تُستخدم خاصية Value الخاصة بـ DataGridViewCellFormattingEventArgs للحصول على قيمة الخلية النصية و لتعيين قيمة عرض الصورة المقابلة.

مثال

Imports System
Imports System.Drawing
Imports System.Windows.Forms

Public Class Form1
    Inherits Form

    Private WithEvents dataGridView1 As New DataGridView()
    Private highPriImage As Bitmap
    Private mediumPriImage As Bitmap
    Private lowPriImage As Bitmap

    Public Sub New()

        ' Initialize the images. 
        Try
            highPriImage = New Bitmap("highPri.bmp")
            mediumPriImage = New Bitmap("mediumPri.bmp")
            lowPriImage = New Bitmap("lowPri.bmp")
        Catch ex As ArgumentException
            MessageBox.Show("The Priority column requires Bitmap images" & _
                "named highPri.bmp, mediumPri.bmp, and lowPri.bmp " & _
                "residing in the same directory as the executable file.")
        End Try

        ' Initialize the DataGridView.
        With dataGridView1
            .Dock = DockStyle.Fill
            .AllowUserToAddRows = False
            .Columns.AddRange( _
                New DataGridViewTextBoxColumn(), _
                New DataGridViewImageColumn())
            .Columns(0).Name = "Balance"
            .Columns(1).Name = "Priority"
            .Rows.Add("-100", "high")
            .Rows.Add("0", "medium")
            .Rows.Add("100", "low")
        End With

        Me.Controls.Add(dataGridView1)

    End Sub

    ' Changes how cells are displayed depending on their columns and values.
    Private Sub dataGridView1_CellFormatting(ByVal sender As Object, _
    ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) _
        Handles dataGridView1.CellFormatting

        ' Set the background to red for negative values in the Balance column.
        If dataGridView1.Columns(e.ColumnIndex).Name.Equals("Balance") Then

            'Dim intValue As Int32
            If CInt(e.Value) < 0 Then
                'if Int32.TryParse((String)e.Value, out intValue) && 
                '   (intValue < 0))

                e.CellStyle.BackColor = Color.Red
                e.CellStyle.SelectionBackColor = Color.DarkRed
            End If
        End If

        ' Replace string values in the Priority column with images.
        If dataGridView1.Columns(e.ColumnIndex).Name.Equals("Priority") Then

            ' Ensure that the value is a string.
            Dim stringValue As String = TryCast(e.Value, String)
            If stringValue Is Nothing Then Return

            ' Set the cell ToolTip to the text value.
            Dim cell As DataGridViewCell = _
                dataGridView1(e.ColumnIndex, e.RowIndex)
            cell.ToolTipText = stringValue

            ' Replace the string value with the image value.
            Select Case stringValue

                Case "high"
                    e.Value = highPriImage
                Case "medium"
                    e.Value = mediumPriImage
                Case "low"
                    e.Value = lowPriImage

            End Select

        End If

    End Sub

    Public Sub Main()
        Application.Run(New Form1())
    End Sub

End Class
using System;
using System.Drawing;
using System.Windows.Forms;

public class Form1 : Form
{
    private DataGridView dataGridView1 = new DataGridView();
    private Bitmap highPriImage;
    private Bitmap mediumPriImage;
    private Bitmap lowPriImage;

    public Form1()
    {
        // Initialize the images. 
        try
        {
            highPriImage = new Bitmap("highPri.bmp");
            mediumPriImage = new Bitmap("mediumPri.bmp");
            lowPriImage = new Bitmap("lowPri.bmp");
        }
        catch (ArgumentException)
        {
            MessageBox.Show("The Priority column requires Bitmap images " +
                "named highPri.bmp, mediumPri.bmp, and lowPri.bmp " +
                "residing in the same directory as the executable file.");
        }

        // Initialize the DataGridView.
        dataGridView1.Dock = DockStyle.Fill;
        dataGridView1.AllowUserToAddRows = false;
        dataGridView1.Columns.AddRange(
            new DataGridViewTextBoxColumn(),
            new DataGridViewImageColumn());
        dataGridView1.Columns[0].Name = "Balance";
        dataGridView1.Columns[1].Name = "Priority";
        dataGridView1.Rows.Add("-100", "high");
        dataGridView1.Rows.Add("0", "medium");
        dataGridView1.Rows.Add("100", "low");
        dataGridView1.CellFormatting +=
            new System.Windows.Forms.DataGridViewCellFormattingEventHandler(
            this.dataGridView1_CellFormatting);
        this.Controls.Add(dataGridView1);
    }

    // Changes how cells are displayed depending on their columns and values.
    private void dataGridView1_CellFormatting(object sender, 
        System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
    {
        // Set the background to red for negative values in the Balance column.
        if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("Balance"))
        {
            Int32 intValue;
            if (Int32.TryParse((String)e.Value, out intValue) && 
                (intValue < 0))
            {
                e.CellStyle.BackColor = Color.Red;
                e.CellStyle.SelectionBackColor = Color.DarkRed;
            }
        }

        // Replace string values in the Priority column with images.
        if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("Priority"))
        {
            // Ensure that the value is a string.
            String stringValue = e.Value as string;
            if (stringValue == null) return;

            // Set the cell ToolTip to the text value.
            DataGridViewCell cell = dataGridView1[e.ColumnIndex, e.RowIndex];
            cell.ToolTipText = stringValue;

            // Replace the string value with the image value.
            switch (stringValue)
            {
                case "high":
                    e.Value = highPriImage;
                    break;
                case "medium":
                    e.Value = mediumPriImage;
                    break;
                case "low":
                    e.Value = lowPriImage;
                    break;
            }
        }
    }

    public static void Main()
    {
        Application.Run(new Form1());
    }

}

التحويل البرمجي للتعليمات البرمجية

يتطلب هذا المثال:

  • مراجع عن تجميعات النظام و تجميعات System.Drawing و System.Windows.Forms.

  • تسمى صور Bitmap بـ highPri.bmp, mediumPri.bmp، و lowPri.bmp الموجودة في نفس الدليل كملف قابل للتنفيذ.

للحصول على المزيد من المعلومات حول إنشاء هذا المثال من خط أوامر Visual Basic أو #Visual C، راجع الإنشاء من سطر الأوامر (Visual Basic) أو إنشاء سطر الأوامر باستخدام csc.exe. يمكنك أيضاً بناء هذا المثال في Visual Studio عن طريق لصق التعليمات البرمجية في مشروع جديد. لمزيد من المعلومات، راجع: كيفية القيام بما يلي: ترجمة و تشغيل مثال التعليمات برمجية لنماذج Windows الكامل باستخدام ‏‫Visual Studio.

راجع أيضًا:

المهام

كيفية القيام بما يلي: تنسيق البيانات في عنصر تحكم DataGridView الخاص بـ Windows Forms

المرجع

DataGridView.DefaultCellStyle

DataGridViewBand.DefaultCellStyle

DataGridView

DataGridViewCellStyle

Bitmap

المبادئ

خلية الأنماط في عرض شبكة البيانات Windows Forms عنصر تحكم

تنسيق البيانات في عنصر تحكم DataGridView Windows Forms

موارد أخرى

عرض البيانات في عنصر التحكم DataGridView Windows Forms