Miguel V
Miguel V

Reputation: 742

How can I ignore tab key in cell input but not tab char? DataGridView C#

For example, I have a string like:

ItemA   MMC FG  MMC 0802    EA  1   21175393

That has 5 tabs on it:

ItemA/tab/MMC FG/tab/MMC 0802/tab/EA/tab/1/tab/21175393

This string is received by a QR Code input being scanned from a tag, now, the problem here is that the input is being done within a cell in a DataGridView, so, when the first tab appears it'll change the selected column to the next one.

Setting the property "StandardTab" to False kinda works, but now when I input the QR Code string it stops the editing mode when the first tab appears. I was trying to use

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if(keyData == Keys.Tab && dGItems.EditingControl != null && msg.HWnd == dGItems.EditingControl.Handle 
                && dGItems.SelectedCells.Cast<DataGridViewCell>().Any(x => x.ColumnIndex ==4))
            {
                return true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

And this helps, but it replaces the tabs from the scanned QR Code string with empty spaces and I don't want this to happen. That has 5 tabs on it:

ItemAMMC FGMMC 0802EA121175393

How can I allow tab inputs in a cell without replacing them or ignoring them? (This is because I need to catch the last tab in order to receive the number next to it)

Upvotes: 2

Views: 130

Answers (1)

Miguel V
Miguel V

Reputation: 742

Solved by:

  1. First, creating two variables: a counter and a string.
int counter = 0;
string keyChar = "";
  1. Next, creating a method to handle the occurrences of a tab key and counting them. When the tab keys repeat N times (in my particular case, 5 times) save the keyChar using KeysConverter.
      public string CatchQRInput(Keys keyData)
        {
            KeysConverter kc = new KeysConverter();
            if (keyData == Keys.Tab) counter++;

            if(counter == 5)
            {
                keyChar += kc.ConvertToString(keyData);
            }
            // Replace the 5th Tab 
            keyChar = keyChar.Replace("Tab", "");
            return keyChar;
        }
  1. Calling the said method into ProcessCmdKey:
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            CatchQRInput(keyData);

            if (keyData == Keys.Tab && dGItems.EditingControl != null && msg.HWnd == dGItems.EditingControl.Handle 
                && dGItems.SelectedCells.Cast<DataGridViewCell>().Any(x => x.ColumnIndex ==4))
            {
                return true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }
  1. With this, the last value will be stored in the string keyChar, this is not the last thing to do, because you can clear the string in order to store multiple values, but for my particular case is enough.

Upvotes: 1

Related Questions