Solved

Gridview keypress

Posted on 2010-08-14
6
1,535 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…

896 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

15 Experts available now in Live!

Get 1:1 Help Now