Click here to Skip to main content
15,890,897 members
Please Sign up or sign in to vote.
1.50/5 (2 votes)
See more:
How to add row to datagrid when i press enter key
Posted

Hi,

Try this

if (e.KeyChar == 13)//enter key
{
DataRow dr = dt.NewRow();
dt.Rows.Add(dr);
DGV.CurrentRowIndex = dt.Rows.Count - 1;
}
 
Share this answer
 
Comments
Mithun P 10-Jan-11 3:57am    
but where to write this code..on page load e.Keychar is not possible
Vigneshb6 10-Jan-11 7:29am    
onkeypress or onkeyup event
if(e.KeyChar == 13)
{
DataTable dtg = (DataTable) DataGrid1.DataSource;
DataRow dr = dtg.NewRow();
dr["Item_ID"]="ItemID";
dr["Item_Name"]="Item Name";
dr["Item_Desc"]="Item Description";
dr["Item_Amount"]="$15.65";
dtg.Rows.Add(dr);
DataGrid1.DataSource = dtg;
It will work for windows. 
If you use DataGrid in ASP then you will have to keep DataTable in Session:
DataTable dtg = new DataTable();
if (Session["SampleDataTable"]==null)
{

DataColumn dc;
dc = new DataColumn("Item_ID",System.Type.GetType("System.String"));
dtg.Columns.Add(dc);
dc = new DataColumn("Item_Name",System.Type.GetType("System.String"));
dtg.Columns.Add(dc);
dc = new DataColumn("Item_Desc",System.Type.GetType("System.String"));
dtg.Columns.Add(dc);
dc = new DataColumn("Item_Amount",System.Type.GetType("System.String"));
dtg.Columns.Add(dc);
}
else {dtg = (DataTable) Session["SampleDataTable"];}

DataRow dr = dtg.NewRow();
dr["Item_ID"]="ItemID";
dr["Item_Name"]="Item Name";
dr["Item_Desc"]="Item Description";
dr["Item_Amount"]="$15.35;
dtg.Rows.Add(dr);
DataGrid1.DataSource=dtg;
DataGrid1.PageSize+=1;
DataGrid1.DataBind();
Session["SampleDataTable"]=dtg;
}


Sample found from HERE[^]

Is it what you looking for ?
 
Share this answer
 
v2
If you want the Grid to respond to Enter key in a custom way,then you have to create a new class that inherits from DataGrid & then override ProcessDialogKey and whenever the user presses Enter, call the method that adds row

This article will give you an idea on the inheriting part

Cheating the DataGridView[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900