Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Gridview keypress

Posted on 2010-08-14
6
Medium Priority
?
1,611 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
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: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering 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

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…
Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…

670 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