Solved

Gridview keypress

Posted on 2010-08-14
6
1,547 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
Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

 
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 500 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

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

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

In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, just open a new email message. In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…

813 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now