DataGridView ve WinForms - validace zadané hodnoty

Giovanna

DataGridView ve WinForms - validace zadané hodnoty
« kdy: 07. 08. 2015, 01:33:08 »
Dobrý den,

používám v mojí desktopové aplikaci DataGridView, který má jeden sloupec editovatelný. Spoléhal jsem na událost CellEndEdit, kde provádím kontrolu, zda-li hodnota odpovídá typu - např. IP adrese. Bohužel, když uživatel zadá nějaký nesmysl, např. písmeno v zmíněné IP adrese, dokážu sice zvalidovat a vyhodit MessageBox, ale co se mi nedaří - ponechat fokus editovanému poli a donutit uživatele k opravě. Uvedu příklad - MessageBox se vyhodí, ale protože uživatel k ukončení editace použil např Enter nebo něco jiného, dojde po vypsání messageboxu k přeskočení na další řádek, další MessageBox a až potom návrat na původní chybnou buňku. Viz přiložený kód, ten Enter nejde cancelnout. Řešili jste prosím někdo toto již někdy? Děkuju i za radu.

Kód: [Vybrat]
        private void paramsGrid_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            int rowIndex = e.RowIndex;

            string typeStr = ((string)paramsGrid.Rows[rowIndex].Cells["Type"].Value);
            VariableType varType = typeStr.ConvertToEnum<VariableType>();

            DataGridViewCell affectedCell = paramsGrid.Rows[rowIndex].Cells["Value"];
            string value = (string)affectedCell.Value;

            if (!ValueValidator.ValueMatch(varType, value))
            {
                MessageBox.Show("ERROR: Value format does not match the " + typeStr + " value type.");

                paramsGrid.CurrentCell = affectedCell;

                paramsGrid.BeginEdit(true);
            }
        }


none_

Re:DataGridView ve WinForms - validace zadané hodnoty
« Odpověď #1 kdy: 07. 08. 2015, 10:23:22 »
Rekl bych, ze zkousis spatne forum...:) Doporucoval bych hledat v anglictine. Hlavne na StackOverflow. Abych jen na sucho neplacal, neco jsem zkusil najit a tohle vypada jako to, co chces. Projdi si tu druhou odpoved.

http://stackoverflow.com/questions/11309520/c-how-to-validate-datagridview-cells

Re:DataGridView ve WinForms - validace zadané hodnoty
« Odpověď #2 kdy: 07. 08. 2015, 10:47:21 »
Ten StackOverFlow mi příjde zbytečně složitý (nevím, pročetl jsem jen asi prvních 10-15 řádků kódu). Jak none_ píše, root není zrovna vhodné místo na tohle. První dotaz na MSDN mi vyhodil tohle:

https://msdn.microsoft.com/en-us/library/ykdxa0bc%28v=vs.90%29.aspx

Implement handlers for the DataGridView control's CellValidating and CellEndEdit events.
Citace
The CellValidating event handler is where you determine whether the value of a cell in the CompanyName column is empty. If the cell value fails validation, set the Cancel property of the System.Windows.Forms.DataGridViewCellValidatingEventArgs class to true. This causes the DataGridView control to prevent the cursor from leaving the cell. Set the ErrorText property on the row to an explanatory string. This displays an error icon with a ToolTip that contains the error text. In the CellEndEdit event handler, set the ErrorText property on the row to the empty string. The CellEndEdit event occurs only when the cell exits edit mode, which it cannot do if it fails validation.

Kód: [Vybrat]
private void dataGridView1_CellValidating(object sender,
    DataGridViewCellValidatingEventArgs e)
{
    string headerText =
        dataGridView1.Columns[e.ColumnIndex].HeaderText;

    // Abort validation if cell is not in the CompanyName column.
    if (!headerText.Equals("CompanyName")) return;

    // Confirm that the cell is not empty.
    if (string.IsNullOrEmpty(e.FormattedValue.ToString()))
    {
        dataGridView1.Rows[e.RowIndex].ErrorText =
            "Company Name must not be empty";
        e.Cancel = true;
    }
}

void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    // Clear the row error in case the user presses ESC.   
    dataGridView1.Rows[e.RowIndex].ErrorText = String.Empty;
}

Snad to pomůže (mělo by, pokud používáš standardní controly).