Home > Software design >  adding an eventhandler to datagridview
adding an eventhandler to datagridview

Time:09-03

I am trying to add a key event handler to a Datagridview.

I have added this (below) to my code:L

private void DgvDb_KeyUp(object sender, KeyEventArgs e)
{
    colI = DgvDb.CurrentCell.ColumnIndex;
    if (colI < 3 | colI == 12 | colI == 13 | colI == 15 | colI == 16 | colI == 17 | colI == 18 | colI == 19 | colI == 20 | colI == 21 | colI == 22)
    {
        vlue = Convert.ToString(DgvDb[colI, rowI - 1].Value);
        DgvDb[colI, rowI].Value = vlue;
    }
}

It shows "0 references" and in the code there is a redline under DgvDB saying it "does not exist in the current context". In the rest of the program, DgvDB is recognized.

I looked at similar code elsewhere in my application and looked at a reference in the XXX.Designer.cs.

I added to my designer under //DgvDB

this.DgvDB.KeyUp  = new System.Windows.Forms.KeyEventHandler(this.DgvDB_KeyUp);

Here, DgvDB_KeyUp is redlined saying does not contain a definition for DgvDB_KeyUp.

CodePudding user response:

I'm sure you wanted to writeif (colI < 3 || colI == 12 || colI == 13 || .....

CodePudding user response:

Double check if the event is tied to the datagridview and thats all:

enter image description here

You should see 1 reference.

Please notice,do not modify the designer since it can be automatically changed.

CodePudding user response:

You could instead have an array of column names and test against them rather than indices.

public partial class Form1 : Form
{

    /// <summary>
    /// Add each column name for logic in DgvDBOnKeyUp
    /// </summary>
    private readonly string[] _columns = new[]
    {
        "Column1", "Column2", "Column3", "Column12",
    };
    public Form1()
    {
        InitializeComponent();


        Shown  = OnShown;
    }

    private void OnShown(object? sender, EventArgs e)
    {
        DgvDB.KeyUp  = DgvDBOnKeyUp;
    }

    private void DgvDBOnKeyUp(object? sender, KeyEventArgs e)
    {
        if (_columns.Contains(DgvDB.CurrentCell.OwningColumn.Name))
        {
            // do your task
        }
    }
}
  • Related