Die Formatierung Der Zelle In DataGridView Auf DataBindingComplete

Ich habe Probleme mit einer Anforderung auf einem meiner Projekte zu arbeiten. Was ich mache, ist verbindlich, eine datatable an ein DataGridView(DGV)'s datasource. Ich habe dann in einer Schleife durch die DataGridView-Eigenschaft und überprüfen, ob die Zelle entweder 1 * oder 2 ** in seinem Wert und formatieren Sie diese Zellen mit einem tooltip und einem roten hintergrund. Wenn ich ein button-Ereignis auslösen, dieser funktioniert auch alles tadellos in Ordnung. Aber wenn ich will, dass das automatisch auftreten, wenn das Formular geladen wird mit dem DataBindingComplete, falls es nicht ordnungsgemäß funktioniert. Das problem war DataBindingComplete wurde feuern mehrere Male. Ich lese diese Frage ALSO, die gab mir ein paar Optionen, um zu versuchen und keiner arbeitete. Hier ist der code:

public partial class TestForm2 : Form
{
    private DataTable dt;
    private int methodCalls = 0;
    private bool isFormatted = false;

    public TestForm2()
    {
        InitializeComponent();
        buildDataTable();
        dataGridView1.DataBindingComplete += dataGridView1_DataBindingComplete;
    }

    private void TestForm2_Load(object sender, EventArgs e)
    {
        bindData();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        formatDataGridView();
    }

    private void bindData()
    {
        dataGridView1.DataSource = dt;
    }

    private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        //If this code is commented out the program will work just fine 
        //by just clicking the button

        //This was added to prevent formatDataGridView from executing more
        //than once.  Even though I unreg and rereg the event handler, the 
        //method was still being called 3 - 4 times. This successfully
        //prevented that but only the *'s were removed and no red back color
        //added to the cells.
        if(!isFormatted)
        {
            formatDataGridView();
        }
    }

    private void buildDataTable()
    {
        dt = new DataTable();

        dt.Columns.Add("col1");
        dt.Columns.Add("col2");
        dt.Columns.Add("col3");
        dt.Columns.Add("col4");
        Random randNum = new Random();
        for(int i = 0; i < 10; i++)
        {
            DataRow dr;
            object[] rowItems = new object[dt.Columns.Count];

            for(int j = 0; j < dt.Columns.Count; j++)
            {
                int number = randNum.Next(1, 20);

                if(number % 7 == 0)
                {
                    rowItems[j] = number + "*";
                }
                else if(number % 5 == 0)
                {
                    rowItems[j] = number + "**";
                }
                else
                {
                    rowItems[j] = number;
                }
            }

            dr = dt.NewRow();
            dr.ItemArray = rowItems;
            dt.Rows.Add(dr);
        }
    }

    private void formatDataGridView()
    {
        //I noticed that I needed to unregister the event handler to 
        //prevent DataBindingComplete from firing during the format
        dataGridView1.DataBindingComplete -= dataGridView1_DataBindingComplete;
        foreach(DataGridViewRow row in dataGridView1.Rows)
        {
            string originalCell;
            string reformattedCell;

            if(row.Cells["col1"].Value != null)
            {
                originalCell = row.Cells["col1"].Value.ToString();

                if (originalCell.Count(c => c == '*') == 2)
                {
                    reformattedCell = originalCell.Replace("**", "");

                    row.Cells["col1"].Value = reformattedCell;
                    row.Cells["col1"].Style.BackColor = Color.Red;
                    row.Cells["col1"].ToolTipText = "Divisible by 5";
                }

                else if (originalCell.Count(c => c == '*') == 1)
                {
                    reformattedCell = originalCell.Replace("*", "");

                    row.Cells["col1"].Value = reformattedCell;
                    row.Cells["col1"].Style.BackColor = Color.Red;
                    row.Cells["col1"].ToolTipText = "Divisible by 7";
                }

                else
                {
                    //do nothing
                }
            }

            if (row.Cells["col2"].Value != null)
            {
                originalCell = row.Cells["col2"].Value.ToString();

                if (originalCell.Count(c => c == '*') == 2)
                {
                    reformattedCell = originalCell.Replace("**", "");

                    row.Cells["col2"].Value = reformattedCell;
                    row.Cells["col2"].Style.BackColor = Color.Red;
                    row.Cells["col2"].ToolTipText = "Divisible by 5";
                }

                if (originalCell.Count(c => c == '*') == 1)
                {
                    reformattedCell = originalCell.Replace("*", "");

                    row.Cells["col2"].Value = reformattedCell;
                    row.Cells["col2"].Style.BackColor = Color.Red;
                    row.Cells["col2"].ToolTipText = "Divisible by 7";
                }

                else
                {
                    //do nothing
                }
            }

            if (row.Cells["col3"].Value != null)
            {
                originalCell = row.Cells["col3"].Value.ToString();

                if (originalCell.Count(c => c == '*') == 2)
                {
                    reformattedCell = originalCell.Replace("**", "");

                    row.Cells["col3"].Value = reformattedCell;
                    row.Cells["col3"].Style.BackColor = Color.Red;
                    row.Cells["col3"].ToolTipText = "Divisible by 5";
                }

                else if (originalCell.Count(c => c == '*') == 1)
                {
                    reformattedCell = originalCell.Replace("*", "");

                    row.Cells["col3"].Value = reformattedCell;
                    row.Cells["col3"].Style.BackColor = Color.Red;
                    row.Cells["col3"].ToolTipText = "Divisible by 7";
                }

                else
                {
                    //do nothing
                }
            }

            if (row.Cells["col4"].Value != null)
            {
                originalCell = row.Cells["col4"].Value.ToString();

                if (originalCell.Count(c => c == '*') == 2)
                {
                    reformattedCell = originalCell.Replace("**", "");

                    row.Cells["col4"].Value = reformattedCell;
                    row.Cells["col4"].Style.BackColor = Color.Red;
                    row.Cells["col4"].ToolTipText = "Divisible by 5";
                }

                else if (originalCell.Count(c => c == '*') == 1)
                {
                    reformattedCell = originalCell.Replace("*", "");

                    row.Cells["col4"].Value = reformattedCell;
                    row.Cells["col4"].Style.BackColor = Color.Red;
                    row.Cells["col4"].ToolTipText = "Divisible by 7";
                }

                else
                {
                    //do nothing
                }
            }
        }
        //Reregistering the event handler
        dataGridView1.DataBindingComplete += dataGridView1_DataBindingComplete;
        isFormatted = true;
        methodCalls++;
        MessageBox.Show("Method Calls: " + methodCalls);
    }
}

Ich bin nicht sicher, wie dieses problem zu umgehen, aber es muss ein Weg sein. Ich bin nicht vertraut mit DataBindingComplete bis vor kurzem, so bin ich sicher, dass hier etwas lernen. Vielen Dank für die Hilfe jeder und hilft mir etwas neues zu lernen!

Versuchen Sie mithilfe des CellFormatting-Ereignis statt.
Was ich denke was falsch läuft ist, während die DataBindEvent, ändern Sie einige Werte in der Startaufstellung. Dann werden diese änderungen gespeichert werden, die in der DataSource, nach dem die DataSource bindet wieder mit den neuen Werten, refiring die DataBindEvent.
Ich glaube, dass dies der Fall ist. Wenn ich nicht die Registrierung der dataGridView1_DataBindingComplete event-handler durch die Angabe dataGridView1.DataBindingComplete -= dataGridView1_DataBindingComplete in meinem formatDataGridView Methode, den Zähler methodCalls Berichte, die die Methode aufgerufen wurde, wie oft gab es änderungen. Allerdings habe ich blockiert dies geschieht, indem Sie die Registrierung der event-handler, um diese änderungen verhindern von feuern der Veranstaltung. Ich habe auch ein bool isFormatted, wird "true" gesetzt, sobald die Methode aufgerufen wird, und die Bedingung if(!isFormatted) auch verhindert, dass diese
Also die dataGridView1_DataBindingComplete Funktion wird mehrfach aufgerufen wird, trotz der Bindung die Funktion von der Veranstaltung?
Ich hätte eine Lösung mit deiner Methode. Ich habe nur neu zu schreiben ein paar Dinge zu testen. Vielen Dank für den input!

InformationsquelleAutor waltmagic | 2014-08-07

Schreibe einen Kommentar