Solved

Gridview keypress

Posted on 2010-08-14
6
1,518 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
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
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

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

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…
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.
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

758 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

20 Experts available now in Live!

Get 1:1 Help Now