I had a gridview mapping a data table in sql sever. this grid will only show user the data, but also will allow user to add new data to the table.
1. we can insert an new empty object to first position of the object list. when user click on the add new row button. the first row will show the edit template to allow user enter new data.
protected void btAddSalesMapping_Click(object sender, EventArgs e)
{
SaleTypeMapping stpm = new SaleTypeMapping();
stpm.ProgramDescription = "";
stpm.SaleType = "";
stpm.SaleTypeCode = "";
stpm.ProgramID = 0;
stpm.SaleTypeMappingID = 0;
SaleTypeMappingProvider stpmProvider = new SaleTypeProgramMappingProvider();
List<SaleTypeMapping> saleTypeMappingList = stpmProvider.GetAllSaleTypeMapping();
if (saleTypeMappingList != null && saleTypeMappingList.Count > 0)
{
dgSaleTypeMapping.EditItemIndex = 0;
dgSaleTypeMapping.CurrentPageIndex = 0;
saleTypeProgramMappingList.Insert(0, stpm);
dgSaleTypeMapping.DataSource = saleTypeMappingList;
dgSaleTypeMapping.DataBind();
}
}
2. we can use ItemType check to verify if the ListItem is Edit Item in dgSaleTypeMapping_ItemDataBound event, if it is true, then we will initialize
those .net Control. this approach will save several round trip to the database, since we do not need them until the user click on the edit button.
protected void dgSaleTypeMapping_ItemDataBound(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.EditItem && dgSaleTypeMapping.EditItemIndex == e.Item.ItemIndex)
{
DropDownList ddlProgram = (DropDownList)e.Item.FindControl("ddlProgram");
FillProgramDropDown(ddlProgram, false);
Label lblProgramId = (Label)e.Item.FindControl("lblProgramId");
if (lblProgramId != null && !string.IsNullOrEmpty(lblProgramId.Text.Trim()))
{
ddlProgram.SelectedIndex =ddlProgram.Items.IndexOf(ddlProgram .Items.FindByValue(lblProgramId.Text));
}
}
}