在获取错误时,用户不应允许进入单元格值中的另一行/列

时间:2016-02-15 06:01:21

标签: c# .net winforms datagridview

在我的Windows窗体中,我的选项卡控件中的验证选项卡控件实现了带有行和列的数据表,如果用户在第二行/列中给出重复的名称与第一行相同的名称,如果用户单击错误按钮,则会出现错误再次用户应该在同一行和列用户不应允许进入另一行/列,所以告诉我如何用户不能允许进入另一个单元格如果用户得到一个错误 请获取单元格离开事件中的代码

2 个答案:

答案 0 :(得分:0)

您应该为数据网格视图的CellValidating事件添加条件,并在需要时调用cancel。请参阅DataGridView.CellValidating Event

    private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        dataGridView1.Rows[e.RowIndex].ErrorText = "";
        // Don't try to validate the 'new row' until finished 
        // editing since there
        // is not any point in validating its initial value.
        if (dataGridView1.Rows[e.RowIndex].IsNewRow) { return; }

        DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
        bool isValid = true;
        // Convert grid view rows to an IEnumerable collection
        IEnumerable<DataGridViewRow> _dataRows = dataGridView1.Rows.Cast<DataGridViewRow>();
        // Loop through grid view rows
        for (int i = 0; i < _dataRows.Count(); i++)
        {
            if(row.Cells[e.ColumnIndex].Value == _dataRows.ElementAt(i).Cells[e.ColumnIndex].Value)
            {
                isValid = false;
                break; // To break from current loop
            }
        }

        if (!isValid)
        {
            e.Cancel = true;
            dataGridView1.Rows[e.RowIndex].ErrorText = "No duplicate values allowed.";
        }
    }

答案 1 :(得分:0)

为什么你对细胞离开事件如此具体。最佳做法是使用dataGridView1_CellValidating事件或dataGridView1_CellValueChanged。 如果您需要获取比较使用的值。

echo '<div class="row">';
if(get_option($shortname.'_custom_text_url','') != "") { 
echo '<p class="welcome-block-text'.get_option($shortname.'_custom_text_url','').'<br>';
} else {
echo '<p class="welcome-block-text">Juan Aquiano<br>';
}

在dataGridView1_CellValueChanged事件中