Answered by:
How to :) mulitple questions

Question
-
User-340993414 posted
Hello I have many questions because a lot of things don't work for my db.
I have 3 tables : contacts, contact_type, service
What I want to do is to edit informations about a contact and create associations between type (of contact) and services. Multiple associations are possibles.
Basics informations about contact (name, email, tel) are in a detail view wich contains a gridview with one or more lines to associate contact with a service.
For example : John Doe is IT manager for Apple service and is Helpdesk for Microsoft service ( :) ).
I create this aspx page :
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="EditContact.aspx.cs" Inherits="SMDBWebApplication.Contacts.EditContact" %> <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Modification Contact</h2> <asp:ValidationSummary ID="editVS" runat="server" ShowSummary="true" ShowMessageBox="false" ValidationGroup="editValidationGroup" ForeColor="Red" /> <asp:ObjectDataSource ID="contactODS" runat="server" DeleteMethod="Delete" InsertMethod="Insert" OldValuesParameterFormatString="original_{0}" SelectMethod="GetDataByID" TypeName="SMDBWebApplication.DAL.InventoryDataSetTableAdapters.ContactsTableAdapter" UpdateMethod="Update" OnUpdated="contactODS_Updated"> <DeleteParameters> <asp:Parameter Name="Original_id" Type="Int32" /> </DeleteParameters> <InsertParameters> <asp:Parameter Name="firstName" Type="String" /> <asp:Parameter Name="lastName" Type="String" /> <asp:Parameter Name="eMail" Type="String" /> <asp:Parameter Name="Tel" Type="String" /> </InsertParameters> <SelectParameters> <asp:QueryStringParameter Name="idParam" QueryStringField="id" Type="Int32" /> </SelectParameters> <UpdateParameters> <asp:Parameter Name="firstName" Type="String" /> <asp:Parameter Name="lastName" Type="String" /> <asp:Parameter Name="eMail" Type="String" /> <asp:Parameter Name="Tel" Type="String" /> <asp:Parameter Name="Original_id" Type="Int32" /> </UpdateParameters> </asp:ObjectDataSource> <asp:DetailsView ID="contactDV" runat="server" Height="50px" DataSourceID="contactODS" DefaultMode="Edit" DataKeyNames="id" AutoGenerateRows="False" OnDataBound="contactDV_DataBound" > <Fields> <%-- ID --%> <asp:TemplateField HeaderText="ID"> <ItemTemplate> <asp:Label ID="idLbl" runat="server" Text='<%# Eval("id") %>' /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Nom : "> <EditItemTemplate> <asp:TextBox ID="lastNameTB" runat="server" Width="250" Text='<%# Bind("lastName") %>' /> <asp:RequiredFieldValidator ID="lastNameRFV" runat="server" ValidationGroup="editValidationGroup" ControlToValidate="lastNameTB" ErrorMessage="Le champs Nom doit être renseigné." ForeColor="Red" Font-Italic="true">*</asp:RequiredFieldValidator> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Prénom : "> <EditItemTemplate> <asp:TextBox ID="firstNameETB" runat="server" Text='<%# Bind("firstName") %>'></asp:TextBox> <asp:RequiredFieldValidator ID="firstNameTBRFV" runat="server" ErrorMessage="Le champs Prénom doit être renseigné." ValidationGroup="editValidationGroup" ControlToValidate="firstNameETB" ForeColor="Red">*</asp:RequiredFieldValidator> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="eMail : "> <EditItemTemplate> <asp:TextBox ID="eMailTB" runat="server" Width="250" Text='<%# Bind("eMail") %>' ClientIDMode="Static" /> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Téléphone : "> <EditItemTemplate> <asp:TextBox ID="telTB" runat="server" ClientIDMode="Static" Text='<%# Bind("Tel") %>' /> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField> <EditItemTemplate> <asp:GridView ID="serviceGV" runat="server" AutoGenerateColumns="false" GridLines="None" ShowFooter="true" OnRowDataBound="serviceGV_RowDataBound" OnRowDeleting="serviceGV_RowDeleting" EmptyDataText="No Data!"> <Columns> <asp:TemplateField HeaderText="Service"> <ItemTemplate> <asp:DropDownList ID="serviceDDL" runat="server" DataTextField="Libelle" DataSourceID="serviceEDS" DataValueField="id" SelectedValue='<%# Eval("idService") %>' AppendDataBoundItems="true" > <asp:ListItem Text="..." Value=""></asp:ListItem> </asp:DropDownList> <asp:TextBox ID="serviceTB" runat="server" Text='<%# Eval("idService") %>'/> <asp:EntityDataSource ID="serviceEDS" runat="server" ConnectionString="name=InventoryEntities" DefaultContainerName="InventoryEntities" EnableFlattening="False" EntitySetName="Tag_Services" OrderBy="it.Libelle" /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Type"> <ItemTemplate> <asp:DropDownList ID="typeDDL" runat="server" DataSourceID="typeEDS" DataTextField="Type" DataValueField="id" SelectedValue='<%# Eval("idType") %>' AppendDataBoundItems="true" > <asp:ListItem Text="..." Value="" /> </asp:DropDownList> <asp:TextBox ID="typeTB" runat="server" /> <asp:EntityDataSource ID="typeEDS" runat="server" ConnectionString="name=InventoryEntities" DefaultContainerName="InventoryEntities" EnableFlattening="False" EntitySetName="ContactType" OrderBy="it.Type" /> </ItemTemplate> <FooterStyle HorizontalAlign="Right" /> <FooterTemplate> <asp:Button ID="addService" runat="server" Text="+" OnClick="addService_Click" /> </FooterTemplate> </asp:TemplateField> <asp:CommandField ShowDeleteButton="true" /> </Columns> </asp:GridView> <asp:ObjectDataSource ID="serviceODS" runat="server" OldValuesParameterFormatString="original_{0}" SelectMethod="GetDataByIdContact" TypeName="SMDBWebApplication.DAL.InventoryDataSetTableAdapters.Contact_ServiceTableAdapter" > <SelectParameters> <asp:QueryStringParameter Name="idContact" QueryStringField="id" Type="Int32" /> </SelectParameters> </asp:ObjectDataSource> </EditItemTemplate> </asp:TemplateField> </Fields> <FooterTemplate> <asp:Button ID="btnUpdate" runat="server" CommandName="Update" Text="Enregistrer" /> </FooterTemplate> </asp:DetailsView> <br /> <div style="float:right"> <asp:Button ID="updateBtn" Text="Enregistrer" runat="server" OnClick="updateBtn_Click" /> </div> </asp:Content>
and code behind :
using SMDBWebApplication; using SMDBWebApplication.DAL; using System; using System.Collections.Generic; using System.Data; using System.Data.Objects.DataClasses; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace SMDBWebApplication.Contacts { public partial class EditContact : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { rowForGridService("serviceGV", "serviceODS", "currentTableService", new string[] {"idService", "idType" }); } } private void rowForGridService(string gv, string ods, string viewState, string[] col) { DataTable dt = new DataTable(); DataTable dtNew = new DataTable(); DataRow drCurrentRow = null; foreach (string oneCol in col) { dtNew.Columns.Add(new DataColumn(oneCol, typeof(string))); } GridView GV = (GridView)contactDV.FindControl(gv); ObjectDataSource ODS = (ObjectDataSource)contactDV.FindControl(ods); dt = ((DataView)ODS.Select()).ToTable(); if (dt.Rows.Count > 0) { for (int i = 0; i < dt.Rows.Count; i++) { drCurrentRow = dtNew.NewRow(); foreach (string oneCol in col) { drCurrentRow[oneCol] = dt.Rows[i][oneCol]; } dtNew.Rows.Add(drCurrentRow); } } ViewState[viewState] = dtNew; GV.DataSource = dtNew; GV.DataBind(); } protected void serviceGV_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { DropDownList serviceDDL = (e.Row.FindControl("serviceDDL") as DropDownList); DropDownList typeDDL = (e.Row.FindControl("typeDDL") as DropDownList); string service = DataBinder.Eval(e.Row.DataItem, "idService").ToString(); string type = DataBinder.Eval(e.Row.DataItem, "idType").ToString(); serviceDDL.Items.FindByValue(service).Selected = true; typeDDL.Items.FindByValue(type).Selected = true; } } protected void serviceGV_RowDeleting(object sender, GridViewDeleteEventArgs e) { GridView csGV = (GridView)contactDV.FindControl("serviceGV"); setRowDataForGridCS(); if (ViewState["currentTableService"] != null) { DataTable dt = (DataTable)ViewState["currentTableService"]; DataRow drCurrentRow = null; int rowIndex = Convert.ToInt32(e.RowIndex); if (dt.Rows.Count > 1) { dt.Rows.Remove(dt.Rows[rowIndex]); drCurrentRow = dt.NewRow(); ViewState["currentTableService"] = dt; csGV.DataSource = dt; csGV.DataBind(); setPreviousDataForGrid(); } else { dt.Rows.Remove(dt.Rows[rowIndex]); drCurrentRow = dt.NewRow(); dt.Rows.Add(drCurrentRow); ViewState["currentTableService"] = dt; csGV.DataSource = dt; csGV.DataBind(); } } } private void setPreviousDataForGrid() { try { GridView GV = (GridView)contactDV.FindControl("serviceGV"); if (ViewState["currentTableService"] != null) { DataTable dt = (DataTable)ViewState["currentTableService"]; if (dt.Rows.Count > 0) { for (int i = 0; i < dt.Rows.Count; i++) { DropDownList serviceDDL = (DropDownList)GV.Rows[i].Cells[0].FindControl("serviceDDL"); DropDownList typeDDL = (DropDownList)GV.Rows[i].Cells[1].FindControl("typeDDL"); serviceDDL.SelectedValue = dt.Rows[i][0].ToString(); typeDDL.SelectedValue = dt.Rows[i][1].ToString(); } } } } catch (Exception) { throw; } } protected void addService_Click(object sender, EventArgs e) { int rowIndex = 0; GridView GV = (GridView)contactDV.FindControl("serviceGV"); if (ViewState["currentTableService"] != null) { DataTable dtCurrentTable = (DataTable)ViewState["currentTableService"]; DataRow drCurrentRow = null; if (dtCurrentTable.Rows.Count > 0) { for (int i = 1; i <= dtCurrentTable.Rows.Count; i++) { drCurrentRow = dtCurrentTable.NewRow(); DropDownList serviceDDL = (DropDownList)GV.Rows[rowIndex].Cells[0].FindControl("serviceDDL"); DropDownList typeDDL = (DropDownList)GV.Rows[rowIndex].Cells[1].FindControl("typeDDL"); //TextBox serviceTxt = (TextBox)GV.Rows[rowIndex].Cells[0].FindControl("serviceTxt"); dtCurrentTable.Rows[i - 1]["idService"] = serviceDDL.SelectedValue; dtCurrentTable.Rows[i - 1]["idType"] = typeDDL.SelectedValue; rowIndex++; } dtCurrentTable.Rows.Add(drCurrentRow); ViewState["currentTableService"] = dtCurrentTable; GV.DataSource = dtCurrentTable; /* for (int i = 0; i < GV.Rows.Count; i++) { DropDownList typeDDL = (DropDownList)GV.Rows[i].Cells[1].FindControl("typeDDL"); typeDDL.Items.Insert(0, new ListItem("...", "")); }*/ GV.DataBind(); } } setPreviousDataForGrid(); } protected void updateBtn_Click(object sender, EventArgs e) { int idContact = int.Parse(Request.QueryString["id"]); RequiredFieldValidator lastNameRFV = ((RequiredFieldValidator)contactDV.FindControl("lastNameRFV")); RequiredFieldValidator firstNameRFV = ((RequiredFieldValidator)contactDV.FindControl("firstNameTBRFV")); lastNameRFV.Validate(); firstNameRFV.Validate(); if (lastNameRFV.IsValid && firstNameRFV.IsValid) { using (InventoryEntities context = new InventoryEntities()) { try { // Charger le contact /*var contact = (from c in context.Contacts where c.id == idContact select c).First(); //Supprimer les données de la table contact_service pour ce contact DAL.InventoryDataSetTableAdapters.Contact_ServiceTableAdapter csTableAdapter = new DAL.InventoryDataSetTableAdapters.Contact_ServiceTableAdapter(); //csTableAdapter.DeleteByIdContact(idContact); //Ajouter les données dans la table contact_service DataTable csTable = (DataTable)ViewState["currentTableService"]; contact.firstName = ((TextBox)contactDV.FindControl("firstNameETB")).Text; contact.lastName = ((TextBox)contactDV.FindControl("lastNameTB")).Text; contact.eMail = ((TextBox)contactDV.FindControl("eMailTB")).Text; contact.Tel = ((TextBox)contactDV.FindControl("telTB")).Text; context.SaveChanges(); //contact.Contact_Service.Add*/ contactODS.UpdateParameters["firstName"].DefaultValue = ((TextBox)contactDV.FindControl("firstNameETB")).Text; contactODS.UpdateParameters["lastName"].DefaultValue = ((TextBox)contactDV.FindControl("lastNameTB")).Text; contactODS.UpdateParameters["eMail"].DefaultValue = ((TextBox)contactDV.FindControl("lastNameTB")).Text; contactODS.UpdateParameters["Tel"].DefaultValue = ((TextBox)contactDV.FindControl("telTB")).Text; contactODS.UpdateParameters["Original_id"].DefaultValue = Request.QueryString["id"]; contactODS.Update(); DAL.InventoryDataSetTableAdapters.Contact_ServiceTableAdapter csTableAdapter = new DAL.InventoryDataSetTableAdapters.Contact_ServiceTableAdapter(); csTableAdapter.DeleteByIdContact(idContact); //Ajouter les données dans la table contact_service setRowDataForGridCS(); DataTable csTable = (DataTable)ViewState["currentTableService"]; for (int i = 0; i < csTable.Rows.Count; i++) { Contact_Service cs = new Contact_Service(); cs.idContact = idContact; cs.idService = Int32.Parse(csTable.Rows[i][0].ToString()); cs.idType = Int32.Parse(csTable.Rows[i][1].ToString()); context.Contact_Service.Add(cs); } context.SaveChanges(); ClientMessageBox.Show("Le contact a été mis à jour.", this); } catch (Exception ex) { } } } } protected void contactODS_Updated(object sender, ObjectDataSourceStatusEventArgs e) { int idContact = int.Parse(Request.QueryString["id"]); using (InventoryEntities context = new InventoryEntities()) { try { DAL.InventoryDataSetTableAdapters.Contact_ServiceTableAdapter csTableAdapter = new DAL.InventoryDataSetTableAdapters.Contact_ServiceTableAdapter(); csTableAdapter.DeleteByIdContact(idContact); //Ajouter les données dans la table contact_service setRowDataForGridCS(); DataTable csTable = (DataTable)ViewState["currentTableService"]; for (int i = 0; i < csTable.Rows.Count; i++) { Contact_Service cs = new Contact_Service(); cs.idContact = idContact; cs.idService = Int32.Parse(csTable.Rows[i][0].ToString()); cs.idType = Int32.Parse(csTable.Rows[i][1].ToString()); context.Contact_Service.Add(cs); } context.SaveChanges(); GridView gv = (GridView)contactDV.FindControl("serviceGV"); ObjectDataSource ods = (ObjectDataSource)contactDV.FindControl("serviceODS"); //gv.DataSource = csTable; //gv.DataBind(); ClientMessageBox.Show("Le contact a été mis à jour.", this); } catch (Exception ex) { } } } private void setRowDataForGridCS() { GridView GV = (GridView)contactDV.FindControl("serviceGV"); if (ViewState["currentTableService"] != null) { DataTable dtCurrentTable = (DataTable)ViewState["currentTableService"]; DataRow drCurrentRow = null; if (dtCurrentTable.Rows.Count > 0) { for (int i = 0; i < dtCurrentTable.Rows.Count; i++) { drCurrentRow = dtCurrentTable.NewRow(); DropDownList serviceDDL = (DropDownList)GV.Rows[i].Cells[0].FindControl("serviceDDL"); DropDownList typeDDL = (DropDownList)GV.Rows[i].Cells[1].FindControl("typeDDL"); dtCurrentTable.Rows[i][0] = serviceDDL.Text; dtCurrentTable.Rows[i][1] = typeDDL.Text; } ViewState["currentTableService"] = dtCurrentTable; } } } protected void contactDV_DataBound(object sender, EventArgs e) { GridView gv = (GridView) contactDV.FindControl("serviceGV"); if (gv.Rows.Count > 0) { var type = gv.Rows[0].RowType; } } } }
This nearly works. But first problem, when I save changes the gridview with associations disappear.
And I want to disable before lines for association when adding new one.
(Sorry for my english).
Hope you could help me. Thanks in advance.
Thursday, August 16, 2018 11:20 AM
Answers
-
User-893317190 posted
Hi miniilo2,
Your empty data is caused by the way you bind your details view's data.
If you bind data through datasourceId property , asp.net will help you bind your data by default.
If you bind your gridview's data before the details view's data binding , it will looks like that you haven't bind data to your gridview.
So if you want to solve your problem , you should bind your gridview's data after the detailsview's databinding.
Below is my code. EntityExeEntities is my dbcontext. And I don't bind data to detailsview through datasourceId.Instead , I bind data manually.
EntityExeEntities entityExeEntities = new EntityExeEntities(); if (!Page.IsPostBack) { int id = Convert.ToInt32((Request["id"] ?? "1")); List<Contact> ts= entityExeEntities.Contacts.Where(c=>c.Id==id).ToList(); contactDV.DataSource = ts; contactDV.DataBind(); rowForGridService("serviceGV", "ObjectDataSource2", "currentTableService", new string[] { "Tag_servicesId", "ContactTypeId" }); } else { int id = Convert.ToInt32((Request["id"] ?? "1")); List<Contact> ts = entityExeEntities.Contacts.Where(c => c.Id == id).ToList(); contactDV.DataSource = ts; contactDV.DataBind(); }
And the detailsview's databound event.
protected void contactDV_DataBound(object sender, EventArgs e) { GridView gv = (GridView)contactDV.FindControl("serviceGV"); if (gv.Rows.Count > 0) { var type = gv.Rows[0].RowType; } DataTable table = ViewState["currentTableService"] as DataTable; gv.DataSource = table; gv.DataBind(); }
If you want to disable a control , just set its Enabled property to false if it has the property in your logic.
<asp:TextBox ID="serviceTB" runat="server" Text='' Enabled="false"/>
Best regards,
Ackerly Xu
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Wednesday, August 22, 2018 7:36 AM
All replies
-
User-893317190 posted
Hi miniilo2,
Your empty data is caused by the way you bind your details view's data.
If you bind data through datasourceId property , asp.net will help you bind your data by default.
If you bind your gridview's data before the details view's data binding , it will looks like that you haven't bind data to your gridview.
So if you want to solve your problem , you should bind your gridview's data after the detailsview's databinding.
Below is my code. EntityExeEntities is my dbcontext. And I don't bind data to detailsview through datasourceId.Instead , I bind data manually.
EntityExeEntities entityExeEntities = new EntityExeEntities(); if (!Page.IsPostBack) { int id = Convert.ToInt32((Request["id"] ?? "1")); List<Contact> ts= entityExeEntities.Contacts.Where(c=>c.Id==id).ToList(); contactDV.DataSource = ts; contactDV.DataBind(); rowForGridService("serviceGV", "ObjectDataSource2", "currentTableService", new string[] { "Tag_servicesId", "ContactTypeId" }); } else { int id = Convert.ToInt32((Request["id"] ?? "1")); List<Contact> ts = entityExeEntities.Contacts.Where(c => c.Id == id).ToList(); contactDV.DataSource = ts; contactDV.DataBind(); }
And the detailsview's databound event.
protected void contactDV_DataBound(object sender, EventArgs e) { GridView gv = (GridView)contactDV.FindControl("serviceGV"); if (gv.Rows.Count > 0) { var type = gv.Rows[0].RowType; } DataTable table = ViewState["currentTableService"] as DataTable; gv.DataSource = table; gv.DataBind(); }
If you want to disable a control , just set its Enabled property to false if it has the property in your logic.
<asp:TextBox ID="serviceTB" runat="server" Text='' Enabled="false"/>
Best regards,
Ackerly Xu
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Wednesday, August 22, 2018 7:36 AM -
User-340993414 posted
Thanks Ackerly Xu it works.
Wednesday, August 22, 2018 7:39 AM