.Net DataGrid does not support inserting since it is dependent on a datasource for its data. You can only update and delete after selecting a particular record from the grid. So the logic for adding a new record on the datagrid is to fill the dataset from the database and inserting a blank row on the datatable.
con.Open();
string strsql = "select * from employees";
SqlDataAdapter da = new SqlDataAdapter(strsql, con);
da.Fill(ds);
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
con.Close();
Add a new button on the page. This will be used for inserting a new row on the grid. On the onClick event of the button, add these lines of code:
1 ds.Tables[0].Rows.Add();
2 DataGrid1.DataSource = ds;
3 DataGrid1.DataBind();
4 int index = DataGrid1.Items.Count - 1;
5 DataGrid1.EditItemIndex = index;
6 DataGrid1.DataBind();
Line 1 is for inserting a blank row at the end of the DataTable. And then binding the DataSet again on the DataGrid. Line 4 is for setting the last row on the DataGrid to Edit mode. Note that DataGrid1.Items.Count-1 is the number of records on the DataGrid minus one, since the index starts at 0, then bind the DataGrid again.
Session["ds"] = ds;
Now, when you click the Add button, the DataGrid will have a new row at the bottom on Edit mode. Notice that the buttons are labeled “Update” and “Cancel”. Your new record will not be saved when you click the Update button since it is designed only for Updating an existing record. We will have to modify the Update_Grid event of the DataGrid. We will include both the update method and the insert method in it since we are using the Edit template of the DataGrid for inserting a new record. And the Update button will trigger the Update_Grid event. We will only have to test if the event is for inserting or updating. To do that, we have to change the text property of the Update Button from “Update” to “Save” and then test the text property on Update_Grid event. The text property will serve as our insert/update tag.
1 if (e.Item.ItemType == ListItemType.EditItem)
2 {
3 if (btnAdd.Enabled == false)
4 {
5 Button btnSave = (Button)e.Item.FindControl("btnUpdate");
6 btnSave.Text = "Save";
7 }
8 }
2/19/2008 2:00:29 PM fragilegirl19
1 comment:
Its really helpful to add new record as we know A grid supports one or more headers. When a single header is used, the grid has Tree List View control behavior, just like the Microsoft Windows Explorer.
Post a Comment