Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Gridview keypress

Posted on 2010-08-14
6
Medium Priority
?
1,625 Views
Last Modified: 2012-06-22
Dear Experts
I am writing a windows application where in I have designed a search form with datagrid view. When user presses enter key, it captures the primary key of selected row. My code is as given below.

private void dgridaccountnature_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (e.KeyChar != (char) Keys.Enter)
                    return;
                GlobalVariable.searchaccountnatureid = "";
                if (dgridaccountnature.CurrentRow != null)
                    GlobalVariable.searchaccountnatureid =
                        Convert.ToString(
                            dgridaccountnature.Rows[dgridaccountnature.CurrentRow.Index - 1].Cells[0
                                ].Value);
                Close();
                masterAccountNature.LoadData();
            }
            catch (Exception)
            {
                string message = StandardMessage.DataAccessError;
                errorProvider.SetError(tbxdescription, message);
            }
        }

Problems:
Example: Let us say I have 3 rows and one blank row in my datagridview, so totally 4 rows inlucluding blank row.
Now when user presses enter key on blank row, it captures the primary key of previous row which is not correct.
For this problem i was suggested to use the following code

 if (e.KeyChar != (char) Keys.Enter || dgridaccountnature.CurrentRow.Index == dgridaccountnature.Rows.Count-1)
                    return;

Now when I use this code, pressing enter on blank row (4th row is solved) but when I press enter on 3rd row having data, nothing happens, i mean it does not capture the primary key id. But only first row it works when i press enter on first row.
0
Comment
Question by:GRChandrashekar
6 Comments
 
LVL 16

Expert Comment

by:kris_per
ID: 33436134

Try removing the -1 in  (dgridaccountnature.CurrentRow.Index - 1) like:

GlobalVariable.searchaccountnatureid = Convert.ToString(dgridaccountnature.Rows[dgridaccountnature.CurrentRow.Index].Cells[0].Value);
0
 
LVL 2

Expert Comment

by:Algol36
ID: 33436179
Use KeyDown event instead of KeyPress:

private void dgridaccountnature_KeyDown(object sender, KeyEventArgs e)
{
            try
            {
                if (e.KeyValue != (char) Keys.Enter)
                    return;
                GlobalVariable.searchaccountnatureid = "";
                if (dgridaccountnature.CurrentRow != null && !dgridaccountnature.CurrentRow.IsNewRow)
                    GlobalVariable.searchaccountnatureid =
                        Convert.ToString(
                            dgridaccountnature.Rows[dgridaccountnature.CurrentRow.Index].Cells[0
                                ].Value);
                Close();
                masterAccountNature.LoadData();
            }
            catch (Exception)
            {
                string message = StandardMessage.DataAccessError;
                errorProvider.SetError(tbxdescription, message);
            }
        }
0
 

Author Comment

by:GRChandrashekar
ID: 33443121
Both the solutions does not work
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 2

Expert Comment

by:Algol36
ID: 33443473
/****This is 100% working code :) ****/

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication39
{
    public partial class Form1 : Form
    {
        DataGridView dgv;

        public Form1()
        {
            dgv = new DataGridView();
            dgv.Parent = this;
            dgv.Columns.Add("Id", "Id");
            dgv.Columns.Add("Column2", "Column2");
            dgv.Rows.Add("1", "a");
            dgv.Rows.Add("2", "b");
            dgv.Rows.Add("3", "c");
            dgv.KeyDown += new KeyEventHandler(dgv_KeyDown);
        }

        void dgv_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue != (char)Keys.Enter)
                return;

            if (dgv.CurrentRow != null && !dgv.CurrentRow.IsNewRow)
            {
                int id;
                if(int.TryParse(dgv.Rows[dgv.CurrentRow.Index].Cells[0].Value.ToString(), out id))
                    MessageBox.Show("id="+id);
            }
        }
    }
}
0
 
LVL 12

Expert Comment

by:starlite551
ID: 33443510
Try adding 1 to the row index.. Doing this will help coz indexes usually start with 0.

dgridaccountnature.Rows[dgridaccountnature.CurrentRow.Index+1].Cells[0].Value);
0
 
LVL 16

Accepted Solution

by:
kris_per earned 2000 total points
ID: 33444172
To get the value from the current selected row, use dgridaccountnature.CurrentRow.Index only. Using -1 will get the value from previous row.

Typically when you hit enter key on a row, it will move the selection to the next row. Key Press event handler is called after the row is moved to the next row; KeyDown event is called before moving the current row to the next.

What your code does is, keypress handler is called after moving to next row; but -1 will read the value from previous row where enter key is hit which is the one required.

But it is better to use KeyDown event with just CurrentRow.Index (without -1 or anything).

In addition to this, also in your code your form is Closed (by Close method) and then a LoadData() method is called...So after the form is closed, if any of the code refers to the form or its controls(datagridview, etc), they wont function properly...So try calling LoadData() and then Close method like:
masterAccountNature.LoadData();
Close();

Below is a simple working code to get the key value...Hope this sample code and the above details would give you better idea.

public partial class Form5 : Form
    {
        private DataGridView dataGridView1;

        public Form5()
        {
            InitializeComponent();

            dataGridView1 = new DataGridView();
            dataGridView1.Location = new Point(10, 10);
            dataGridView1.Size = new Size(200, 200);
            this.Controls.Add(dataGridView1);

            dataGridView1.Columns.Add("Id","Id");
            dataGridView1.Columns.Add("Name", "Name");
            dataGridView1.Rows.Add("102317", "Name1");
            dataGridView1.Rows.Add("202317", "Name2");

            dataGridView1.KeyDown += new KeyEventHandler(dataGridView1_KeyDown);            
        }

        void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {            
            if (e.KeyValue != (char)Keys.Enter)
                return;

            if (dataGridView1.CurrentRow != null)
            {
                string key
                    = Convert.ToString(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value);
            }
        }
    }

Open in new window

0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Look below the covers at a subform control , and the form that is inside it. Explore properties and see how easy it is to aggregate, get statistics, and synchronize results for your data. A Microsoft Access subform is used to show relevant calcul…
Suggested Courses

916 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question