Add Values in Gridview Using ENTER KEY






4.90/5 (6 votes)
This tip shows you how to add the Values in Gridview using ENTER key...
Introduction
In this tip, I am going to show you how to add the values in gridview
by pressing ENTER KEY.
Using the Code
Create an Empty Windows Form. Add a Datagridview
and Textbox
in the Form
.
Select Key Press Event in Property Window and Name
method. Paste the below code. That may do the work:
void TextBox1KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
{
{
string dates= textBox1.Text.ToString(); // assign the Textbox value to a string
int i=dataGridView1.Rows.Count; // count the Number of available rows in the GridView
int j=i-1; //counted the Rows minus 1 that will make you add Rows
this.dataGridView1.Rows.Add(); // create the Rows if it is needed
dataGridView1.Rows[j].Cells[0].Value=dates; // add the Values to the GridView
textBox1.Text=""; //Empty the Textbox
}
}
Let's explain the code line by line:
int i=dataGridView1.Rows.Count;
This line allows to Count the Number of rows available in the Gridview
and it has been assigned to the Variable i
.
this.dataGridView1.Rows.Add();
This code allows to create only one Row at a time.
dataGridView1.Rows[j].Cells[0].Value=dates;
This allows us to Add the value to the gridview
.
dataGridView1.Rows[RowIndex].Cells[CellIndex].Value;
Row Index may change according to the values available in the Gridview
.
Or we can ignore all the above lines and use the line below.
It allow us add the Data and create Rows in the Gridview
.
dataGridView.Rows.Add(datas);
I think this may help all of you.