This question already has an answer here:
GridView's UpdateMethod not firing
(1 answer)
update linq related table
Closed 9 years ago.
I have two table, they are parent child. testtypes(Id,Name), testusers(Id,TypeId,Name)
i want update them in gridview. testusers (name filed) was updated but testTypes(testtype.Name field) doesn't update.
there is no exception. (i check the e.exception == null variable in GridviewUpdated handler.)
i'm really confuesd! it's so strange. i think vs 2012 has bug!
here's my markup and code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm4.aspx.cs" Inherits="Ahooratech.WebForm4" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView runat="server" ID="gv" AutoGenerateColumns="False" DataKeyNames="Id" DataSourceID="LinqDataSource1">
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="True" SortExpression="Id" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="testtype.Name" HeaderText="mytypid" />
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="LinqDataSource1" runat="server" ContextTypeName="Ahooratech.DAL.DataClasses1DataContext" EnableUpdate="True" EntityTypeName="" TableName="testusers">
</asp:LinqDataSource>
</div>
</form>
</body>
</html>
and:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Ahooratech
{
public partial class WebForm4 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
gv.rowUpdated += handler;
}
void gv_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
if (e.exception == null)
{
resultlbl.text = "Update seccessfully";// i get this message and name update in db
}
}
}
}
and DAL:
[global::System.Data.Linq.Mapping.DatabaseAttribute(Name="AhooraTechdb")]
public partial class DataClasses1DataContext : System.Data.Linq.DataContext
{
private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();
public DataClasses1DataContext() :
base(global::System.Configuration.ConfigurationManager.ConnectionStrings["AhooraTechdbConnectionString1"].ConnectionString, mappingSource)
{
OnCreated();
}
public DataClasses1DataContext(string connection) :
base(connection, mappingSource)
{
OnCreated();
}
public DataClasses1DataContext(System.Data.IDbConnection connection) :
base(connection, mappingSource)
{
OnCreated();
}
public DataClasses1DataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) :
base(connection, mappingSource)
{
OnCreated();
}
public DataClasses1DataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) :
base(connection, mappingSource)
{
OnCreated();
}
public System.Data.Linq.Table<AdminUser> AdminUsers
{
get
{
return this.GetTable<AdminUser>();
}
}
public System.Data.Linq.Table<WishProduct> WishProducts
{
get
{
return this.GetTable<WishProduct>();
}
}
public System.Data.Linq.Table<Advertisement> Advertisements
{
get
{
return this.GetTable<Advertisement>();
}
}
public System.Data.Linq.Table<aspnet_Application> aspnet_Applications
{
get
{
return this.GetTable<aspnet_Application>();
}
}
public System.Data.Linq.Table<aspnet_Membership> aspnet_Memberships
{
get
{
return this.GetTable<aspnet_Membership>();
}
}
public System.Data.Linq.Table<aspnet_SchemaVersion> aspnet_SchemaVersions
{
get
{
return this.GetTable<aspnet_SchemaVersion>();
}
}
public System.Data.Linq.Table<aspnet_User> aspnet_Users
{
get
{
return this.GetTable<aspnet_User>();
}
}
public System.Data.Linq.Table<BillingType> BillingTypes
{
get
{
return this.GetTable<BillingType>();
}
}
public System.Data.Linq.Table<BoolValue> BoolValues
{
get
{
return this.GetTable<BoolValue>();
}
}
public System.Data.Linq.Table<ContainerItem> ContainerItems
{
get
{
return this.GetTable<ContainerItem>();
}
}
public System.Data.Linq.Table<Container> Containers
{
get
{
return this.GetTable<Container>();
}
}
public System.Data.Linq.Table<Country> Countries
{
get
{
return this.GetTable<Country>();
}
}
public System.Data.Linq.Table<DeliveryTimeType> DeliveryTimeTypes
{
get
{
return this.GetTable<DeliveryTimeType>();
}
}
public System.Data.Linq.Table<DeliveryType> DeliveryTypes
{
get
{
return this.GetTable<DeliveryType>();
}
}
public System.Data.Linq.Table<DescriptiveValue> DescriptiveValues
{
get
{
return this.GetTable<DescriptiveValue>();
}
}
public System.Data.Linq.Table<DiscountCode> DiscountCodes
{
get
{
return this.GetTable<DiscountCode>();
}
}
public System.Data.Linq.Table<DiscountCodesPrice> DiscountCodesPrices
{
get
{
return this.GetTable<DiscountCodesPrice>();
}
}
public System.Data.Linq.Table<DiscountcodesProduct> DiscountcodesProducts
{
get
{
return this.GetTable<DiscountcodesProduct>();
}
}
public System.Data.Linq.Table<DiscountCodesUser> DiscountCodesUsers
{
get
{
return this.GetTable<DiscountCodesUser>();
}
}
public System.Data.Linq.Table<DiscountType> DiscountTypes
{
get
{
return this.GetTable<DiscountType>();
}
}
public System.Data.Linq.Table<MeasurmentValue> MeasurmentValues
{
get
{
return this.GetTable<MeasurmentValue>();
}
}
public System.Data.Linq.Table<ProductImage> ProductImages
{
get
{
return this.GetTable<ProductImage>();
}
}
public System.Data.Linq.Table<ProductOption> ProductOptions
{
get
{
return this.GetTable<ProductOption>();
}
}
public System.Data.Linq.Table<ProductProductOption> ProductProductOptions
{
get
{
return this.GetTable<ProductProductOption>();
}
}
public System.Data.Linq.Table<Product> Products
{
get
{
return this.GetTable<Product>();
}
}
public System.Data.Linq.Table<ProductsCat> ProductsCats
{
get
{
return this.GetTable<ProductsCat>();
}
}
public System.Data.Linq.Table<ProductsDescriptionImage> ProductsDescriptionImages
{
get
{
return this.GetTable<ProductsDescriptionImage>();
}
}
public System.Data.Linq.Table<ProductsPeripheralProduct> ProductsPeripheralProducts
{
get
{
return this.GetTable<ProductsPeripheralProduct>();
}
}
public System.Data.Linq.Table<ProductsProperty> ProductsProperties
{
get
{
return this.GetTable<ProductsProperty>();
}
}
public System.Data.Linq.Table<ProductsRelatedProduct> ProductsRelatedProducts
{
get
{
return this.GetTable<ProductsRelatedProduct>();
}
}
public System.Data.Linq.Table<Property> Properties
{
get
{
return this.GetTable<Property>();
}
}
public System.Data.Linq.Table<PropertyCat> PropertyCats
{
get
{
return this.GetTable<PropertyCat>();
}
}
public System.Data.Linq.Table<RetrurnedOrder> RetrurnedOrders
{
get
{
return this.GetTable<RetrurnedOrder>();
}
}
public System.Data.Linq.Table<ReturnCause> ReturnCauses
{
get
{
return this.GetTable<ReturnCause>();
}
}
public System.Data.Linq.Table<ShippingType> ShippingTypes
{
get
{
return this.GetTable<ShippingType>();
}
}
public System.Data.Linq.Table<ShortDescriptiveValue> ShortDescriptiveValues
{
get
{
return this.GetTable<ShortDescriptiveValue>();
}
}
public System.Data.Linq.Table<SqlDataType> SqlDataTypes
{
get
{
return this.GetTable<SqlDataType>();
}
}
public System.Data.Linq.Table<State> States
{
get
{
return this.GetTable<State>();
}
}
public System.Data.Linq.Table<StatesShippingType> StatesShippingTypes
{
get
{
return this.GetTable<StatesShippingType>();
}
}
public System.Data.Linq.Table<StockStateType> StockStateTypes
{
get
{
return this.GetTable<StockStateType>();
}
}
public System.Data.Linq.Table<test> tests
{
get
{
return this.GetTable<test>();
}
}
public System.Data.Linq.Table<Unit> Units
{
get
{
return this.GetTable<Unit>();
}
}
public System.Data.Linq.Table<UserRequestProduct> UserRequestProducts
{
get
{
return this.GetTable<UserRequestProduct>();
}
}
public System.Data.Linq.Table<User> Users
{
get
{
return this.GetTable<User>();
}
}
public System.Data.Linq.Table<Warranty> Warranties
{
get
{
return this.GetTable<Warranty>();
}
}
public System.Data.Linq.Table<SideBarMenuItem> SideBarMenuItems
{
get
{
return this.GetTable<SideBarMenuItem>();
}
}
public System.Data.Linq.Table<OrderItem> OrderItems
{
get
{
return this.GetTable<OrderItem>();
}
}
public System.Data.Linq.Table<UserAddress> UserAddresses
{
get
{
return this.GetTable<UserAddress>();
}
}
public System.Data.Linq.Table<Basket> Baskets
{
get
{
return this.GetTable<Basket>();
}
}
public System.Data.Linq.Table<ElseCost> ElseCosts
{
get
{
return this.GetTable<ElseCost>();
}
}
public System.Data.Linq.Table<OrderStatuse> OrderStatuses
{
get
{
return this.GetTable<OrderStatuse>();
}
}
public System.Data.Linq.Table<ShipmentStatuse> ShipmentStatuses
{
get
{
return this.GetTable<ShipmentStatuse>();
}
}
public System.Data.Linq.Table<ConfirmStatuse> ConfirmStatuses
{
get
{
return this.GetTable<ConfirmStatuse>();
}
}
public System.Data.Linq.Table<PaymentStatuse> PaymentStatuses
{
get
{
return this.GetTable<PaymentStatuse>();
}
}
public System.Data.Linq.Table<Order> Orders
{
get
{
return this.GetTable<Order>();
}
}
public System.Data.Linq.Table<testtype> testtypes
{
get
{
return this.GetTable<testtype>();
}
}
public System.Data.Linq.Table<testuser> testusers
{
get
{
return this.GetTable<testuser>();
}
}
[global::System.Data.Linq.Mapping.FunctionAttribute(Name="dbo.FetchProperties")]
public ISingleResult<FetchPropertiesResult> FetchProperties([global::System.Data.Linq.Mapping.ParameterAttribute(Name="ProductId", DbType="Int")] System.Nullable<int> productId)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), productId);
return ((ISingleResult<FetchPropertiesResult>)(result.ReturnValue));
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.testtypes")]
public partial class testtype : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _Id;
private string _Name;
private EntitySet<testuser> _testusers;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnIdChanging(int value);
partial void OnIdChanged();
partial void OnNameChanging(string value);
partial void OnNameChanged();
#endregion
public testtype()
{
this._testusers = new EntitySet<testuser>(new Action<testuser>(this.attach_testusers), new Action<testuser>(this.detach_testusers));
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Id", DbType="Int NOT NULL", IsPrimaryKey=true)]
public int Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this.OnIdChanging(value);
this.SendPropertyChanging();
this._Id = value;
this.SendPropertyChanged("Id");
this.OnIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Name", DbType="NVarChar(50)")]
public string Name
{
get
{
return this._Name;
}
set
{
if ((this._Name != value))
{
this.OnNameChanging(value);
this.SendPropertyChanging();
this._Name = value;
this.SendPropertyChanged("Name");
this.OnNameChanged();
}
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="testtype_testuser", Storage="_testusers", ThisKey="Id", OtherKey="TypeId")]
public EntitySet<testuser> testusers
{
get
{
return this._testusers;
}
set
{
this._testusers.Assign(value);
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private void attach_testusers(testuser entity)
{
this.SendPropertyChanging();
entity.testtype = this;
}
private void detach_testusers(testuser entity)
{
this.SendPropertyChanging();
entity.testtype = null;
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.testusers")]
public partial class testuser : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _Id;
private string _Name;
private System.Nullable<int> _TypeId;
private EntityRef<testtype> _testtype;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnIdChanging(int value);
partial void OnIdChanged();
partial void OnNameChanging(string value);
partial void OnNameChanged();
partial void OnTypeIdChanging(System.Nullable<int> value);
partial void OnTypeIdChanged();
#endregion
public testuser()
{
this._testtype = default(EntityRef<testtype>);
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Id", DbType="Int NOT NULL", IsPrimaryKey=true)]
public int Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this.OnIdChanging(value);
this.SendPropertyChanging();
this._Id = value;
this.SendPropertyChanged("Id");
this.OnIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Name", DbType="NVarChar(50)")]
public string Name
{
get
{
return this._Name;
}
set
{
if ((this._Name != value))
{
this.OnNameChanging(value);
this.SendPropertyChanging();
this._Name = value;
this.SendPropertyChanged("Name");
this.OnNameChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_TypeId", DbType="Int")]
public System.Nullable<int> TypeId
{
get
{
return this._TypeId;
}
set
{
if ((this._TypeId != value))
{
if (this._testtype.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OnTypeIdChanging(value);
this.SendPropertyChanging();
this._TypeId = value;
this.SendPropertyChanged("TypeId");
this.OnTypeIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="testtype_testuser", Storage="_testtype", ThisKey="TypeId", OtherKey="Id", IsForeignKey=true)]
public testtype testtype
{
get
{
return this._testtype.Entity;
}
set
{
testtype previousValue = this._testtype.Entity;
if (((previousValue != value)
|| (this._testtype.HasLoadedOrAssignedValue == false)))
{
this.SendPropertyChanging();
if ((previousValue != null))
{
this._testtype.Entity = null;
previousValue.testusers.Remove(this);
}
this._testtype.Entity = value;
if ((value != null))
{
value.testusers.Add(this);
this._TypeId = value.Id;
}
else
{
this._TypeId = default(Nullable<int>);
}
this.SendPropertyChanged("testtype");
}
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public partial class FetchPropertiesResult
{
private int _ProdPropId;
private string _propertyName;
private string _UnitName;
private string _propertyCatName;
private string _sqlType;
private string _stringVal;
private string _shortStringVal;
private System.Nullable<int> _measurmentVal;
private System.Nullable<bool> _boolVal;
private int _OrderId;
public FetchPropertiesResult()
{
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ProdPropId", DbType="Int NOT NULL")]
public int ProdPropId
{
get
{
return this._ProdPropId;
}
set
{
if ((this._ProdPropId != value))
{
this._ProdPropId = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_propertyName", DbType="NVarChar(50) NOT NULL", CanBeNull=false)]
public string propertyName
{
get
{
return this._propertyName;
}
set
{
if ((this._propertyName != value))
{
this._propertyName = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_UnitName", DbType="NVarChar(50)")]
public string UnitName
{
get
{
return this._UnitName;
}
set
{
if ((this._UnitName != value))
{
this._UnitName = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_propertyCatName", DbType="NVarChar(50) NOT NULL", CanBeNull=false)]
public string propertyCatName
{
get
{
return this._propertyCatName;
}
set
{
if ((this._propertyCatName != value))
{
this._propertyCatName = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_sqlType", DbType="NVarChar(20) NOT NULL", CanBeNull=false)]
public string sqlType
{
get
{
return this._sqlType;
}
set
{
if ((this._sqlType != value))
{
this._sqlType = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_stringVal", DbType="NVarChar(MAX)")]
public string stringVal
{
get
{
return this._stringVal;
}
set
{
if ((this._stringVal != value))
{
this._stringVal = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_shortStringVal", DbType="NVarChar(100)")]
public string shortStringVal
{
get
{
return this._shortStringVal;
}
set
{
if ((this._shortStringVal != value))
{
this._shortStringVal = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_measurmentVal", DbType="Int")]
public System.Nullable<int> measurmentVal
{
get
{
return this._measurmentVal;
}
set
{
if ((this._measurmentVal != value))
{
this._measurmentVal = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_boolVal", DbType="Bit")]
public System.Nullable<bool> boolVal
{
get
{
return this._boolVal;
}
set
{
if ((this._boolVal != value))
{
this._boolVal = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_OrderId", DbType="Int NOT NULL")]
public int OrderId
{
get
{
return this._OrderId;
}
set
{
if ((this._OrderId != value))
{
this._OrderId = value;
}
}
}
}
Related
There is need to show all parts of one area. I created new form PMCContractAreasDialog. When I click on specific contract line into contract form it should open new form and show all parts of one area. In sum there should be same like on contract line. But every time when I click on button form is empty. Am I missing something ?
[Form]
public class PMCContractAreasDialog extends FormRun
{
[FormObservable]
date currWorkingDate;
[FormObservable]
boolean commonAreasRead;
PMERentalObjectAreaValueCl tmpRentalAreaCl;
PMETmpRentalObjectArea tmpArea;
public void init ()
{
super();
pmcContractLine_ds.linkActive();
}
public void activate(boolean _active)
{
PMCContractArea contractArea;
AmountMST sumContractArea;
pmcContractLine_ds.readCommonAreas(pmcContractLine);
h1_h2.realValue(pmcContractLine_ds.h1_h2(pmcContractLine));
efa.realValue(pmcContractLine_ds.efa(pmcContractLine));
bfa.realValue(pmcContractLine_ds.bfa(pmcContractLine));
mfa.realValue(pmcContractLine_ds.mfa(pmcContractLine));
sumArea.realValue(h1_h2.realValue() + efa.realValue() + bfa.realValue() + mfa.realValue());
}
[DataSource]
class PMCContract
{
public int active()
{
int ret;
ret = super();
return ret;
}
}
[DataSource]
class PMCContractLine
{
public int active()
{
int ret;
ret = super();
return ret;
}
display PMEAreaCommonBuildingSum BFA(PMCContractLine _contractLine)
{
if (commonAreasRead)
{
if (_contractLine.RentalObjectId)
{
return PMERentalObjectAreaCl::getRentalObjectCommonAreaBuildingSum(_contractLine.RentalObjectId, currWorkingDate, tmpArea, false);
}
else
{
return 0;
}
}
return 0;
}
void readCommonAreas(PMCContractLine _contractLine)
{
if (!commonAreasRead)
{
if (pmcContractLine.RentalObjectId)
{
tmpRentalAreaCl = new PMERentalObjectAreaValueCl();
tmpRentalAreaCl.clear();
tmpRentalAreaCl.getRentalObjectAreas(_contractLine.RentalObjectId, PMGUser::find().currDate());
tmpArea.setTmpData(tmpRentalAreaCl.getTempTable());
commonAreasRead = true;
}
}
}
//BP Deviation Documented
display PMEAreaCommonSectionSum EFA(PMCContractLine _contractLine)
{
if (commonAreasRead)
{
if (_contractLine.RentalObjectId)
{
return PMERentalObjectAreaCl::getRentalObjectCommonAreaSectionSum(_contractLine.RentalObjectId, currWorkingDate, tmpArea, false);
}
else
{
return 0;
}
}
return 0;
}
//BP Deviation Documented
display PMEAreaTotal H1_H2(PMCContractLine _contractLine)
{
if (commonAreasRead)
{
if (_contractLine.RentalObjectId)
{
return PMERentalObjectAreaCl::getRentalObjectMainAreaSectionSum(_contractLine.RentalObjectId, currWorkingDate, tmpArea, false);
}
else
{
return 0;
}
}
return 0;
}
//BP Deviation Documented
display PMEAreaTotal MFA(PMCContractLine _contractLine)
{
if (commonAreasRead)
{
if (_contractLine.RentalObjectId)
{
return PMERentalObjectAreaCl::getRentalObjectCommonAreaFixedSum(_contractLine.RentalObjectId, currWorkingDate, tmpArea, false);
}
else
{
return 0;
}
}
return 0;
}
}
[DataSource]
class PMCContractArea
{
public void delete()
{
super();
this.updateLines();
}
public void write()
{
super();
this.updateLines();
}
void updateLines()
{
;
PMCContractArea::updateLineAreas(pmcContractArea.ContractId, pmcContractArea.RentalObjectId);
}
}
}
Interesting. I have a control QuickContacts with Contacts collection. When I declare Contacts of type List<Contact> it works perfectly, but when use ContactsList<Contact> which is a Generic that implements IList<T> it gives "Parser Error : Type 'Controls.ContactList'1[[Controls.Contact, Controls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' does not have a public property named 'Contact'."
Here, this code works perfectly with List<Contact>
[DefaultProperty("Contacts"),
ParseChildren(true, "Contacts"),
ToolboxData("<{0}:QuickContacts runat=server></{0}:QuickContacts>")]
public class QuickContacts : WebControl
{
private List<Contact> contactsList;
[Category("Behavior"),
Description("The contacts collection."),
DesignerSerializationVisibility(
DesignerSerializationVisibility.Content),
PersistenceMode(PersistenceMode.InnerDefaultProperty)]
public List<Contact> Contacts
{
get
{
if (contactsList == null)
{
contactsList = new List<Contact>();
}
return contactsList;
}
}
I want to provide a Contacts collection that maintains state so I replace using List<Contacts> with custom ContactsList that implements IList<T>, IStateManager. When use IList<T> instead of List<T>, it doesn't work. Here is the
public class ContactList<T> : IList<T>, IStateManager
{
Then I use it as following:
[DefaultProperty("Contacts"),
ParseChildren(true, "Contacts"),
ToolboxData("<{0}:QuickContacts runat=server></{0}:QuickContacts>")]
public class QuickContacts : WebControl
{
private ContactList<Contact> contactsList;
[Category("Behavior"),
Description("The contacts collection."),
DesignerSerializationVisibility(
DesignerSerializationVisibility.Content),
PersistenceMode(PersistenceMode.InnerDefaultProperty)]
public ContactList<Contact> Contacts
{
get
{
if (contactsList == null)
{
contactsList = new ContactList<Contact>();
}
return contactsList;
}
}
"Parser Error : Type 'Controls.ContactList'1[[Controls.Contact, Controls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' does not have a public property named 'Contact'."
Parser Error at <cc1:Contact Name=
<asp:Content ID="Content2" ContentPlaceHolderID="Main" runat="server">
<cc1:QuickContacts ID="QuickContacts1" runat="server" BorderStyle="Solid" BorderWidth="1px">
<cc1:Contact Name="someone" Email="someone#example.com"
Phone="(555) 555-0100" />
I read many posts about List<T> vs IList<T> but that still doesn't answer the question. What difference between List<T> and a class that implements IList<T> which causes this error?
Here is the answer, when reviewed List<T> implementation at Microsoft http://referencesource.microsoft.com
[DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public class List<T> : IList<T>, System.Collections.IList, IReadOnlyList<T>
{
It implements System.Collections.IList too. And this was the point.
And here is the full working code.
[DefaultProperty("Contacts"),
ParseChildren(true, ChildrenAsProperties = true, DefaultProperty = "Contacts"),
ToolboxData("<{0}:QuickContacts runat=server></{0}:QuickContacts>")]
public class QuickContacts : WebControl
{
private StateManagedCollection<Contact> contactsList;
[Category("Behavior"),
Description("The contacts collection."),
DesignerSerializationVisibility(
DesignerSerializationVisibility.Content),
PersistenceMode(PersistenceMode.InnerDefaultProperty)]
public StateManagedCollection<Contact> Contacts
{
get
{
if (contactsList == null)
{
contactsList = new StateManagedCollection<Contact>();
}
return contactsList;
}
}
protected override void RenderContents(HtmlTextWriter writer)
{
Table t = CreateContactsTable();
if (t != null)
{
t.RenderControl(writer);
}
}
private Table CreateContactsTable()
{
Table t = null;
if (contactsList != null && contactsList.Count > 0)
{
t = new Table();
foreach (Contact item in contactsList)
{
Contact aContact = item as Contact;
if (aContact != null)
{
TableRow row = new TableRow();
TableCell c1 = new TableCell();
c1.Text = aContact.Name;
row.Controls.Add(c1);
TableCell c2 = new TableCell();
c2.Text = aContact.Email;
row.Controls.Add(c2);
TableCell c3 = new TableCell();
c3.Text = aContact.Phone;
row.Controls.Add(c3);
t.Controls.Add(row);
}
}
}
return t;
}
protected override void LoadViewState(object savedState)
{
if (savedState != null)
{
Pair p = savedState as Pair;
base.LoadViewState(p.First);
contactsList.LoadViewState(p.Second);
}
}
protected override object SaveViewState()
{
Pair p = new Pair(base.SaveViewState(), contactsList.SaveViewState());
return p;
}
protected override void TrackViewState()
{
base.TrackViewState();
contactsList.TrackViewState();
}
}
And here is the StateManagedCollection
public class StateManagedCollection<T> : IList<T>, System.Collections.IList, IReadOnlyList<T>, IStateManager
where T : StateManagedClass, new()
{
private List<T> lst = default(List<T>);
private Boolean isTrackingViewState = default(Boolean);
private Boolean saveAll = default(Boolean);
public StateManagedCollection()
{
lst = new List<T>();
isTrackingViewState = false;
saveAll = false;
}
public void SetMarked()
{
for (int i = 0; i < lst.Count; i++)
{
lst[i].SetMarked();
}
}
public bool IsTrackingViewState
{
get { return isTrackingViewState; }
}
public void LoadViewState(object state)
{
if (state != null)
{
if (state is List<Object>)
{
// all items were saved
List<Object> allItems = (List<Object>)state;
saveAll = true;
Int32 count = lst.Count;
for (int i = 0; i < allItems.Count; i++)
{
if (i < count)
lst[i].LoadViewState(allItems[i]);
else
{
T item = new T();
item.LoadViewState(allItems[i]);
lst.Add(item);
}
}
}
else if (state is Dictionary<Int32, Object>)
{
Dictionary<Int32, Object> changedItems = (Dictionary<Int32, Object>)state;
foreach (KeyValuePair<Int32, Object> item in changedItems)
{
if (item.Key < lst.Count)
lst[item.Key].LoadViewState(item.Value);
}
}
}
}
public object SaveViewState()
{
if (saveAll)
{
List<Object> allItems = new List<Object>();
foreach (var item in lst)
{
item.SetMarked();
allItems.Add(item.SaveViewState());
}
return allItems;
}
else
{
Dictionary<Int32, Object> changedItems = new Dictionary<Int32, Object>();
for (int i = 0; i < lst.Count; i++)
{
Object state = lst[i].SaveViewState();
if (state != null)
{
changedItems.Add(i, state);
}
}
return changedItems;
}
}
public void TrackViewState()
{
isTrackingViewState = true;
for (int i = 0; i < lst.Count; i++)
{
lst[i].TrackViewState();
}
}
public int IndexOf(T item)
{
return lst.IndexOf(item);
}
public void Insert(int index, T item)
{
lst.Insert(index, item);
if (isTrackingViewState)
saveAll = true;
}
public void RemoveAt(int index)
{
lst.RemoveAt(index);
if (isTrackingViewState)
saveAll = true;
}
public T this[int index]
{
get
{
return lst[index];
}
set
{
lst[index] = value;
}
}
public void Add(T item)
{
lst.Add(item);
if (isTrackingViewState)
saveAll = true;
}
public void Clear()
{
lst.Clear();
if (isTrackingViewState)
saveAll = true;
}
public bool Contains(T item)
{
return lst.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
lst.CopyTo(array, arrayIndex);
}
public int Count
{
get { return lst.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(T item)
{
Boolean rslt = lst.Remove(item);
if (isTrackingViewState)
saveAll = true;
return rslt;
}
public IEnumerator<T> GetEnumerator()
{
return lst.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public int Add(object value)
{
Add((T)value);
return Count - 1;
}
public bool Contains(object value)
{
return Contains((T)value);
}
public int IndexOf(object value)
{
return IndexOf((T)value);
}
public void Insert(int index, object value)
{
Insert(index, (T)value);
}
public bool IsFixedSize
{
get { return ((IList)lst).IsFixedSize; }
}
public void Remove(object value)
{
Remove((T)value);
}
object IList.this[int index]
{
get
{
return lst[index];
}
set
{
lst[index] = (T)value;
}
}
public void CopyTo(Array array, int index)
{
CopyTo((T[])array, index);
}
public bool IsSynchronized
{
get { return ((ICollection)lst).IsSynchronized; }
}
public object SyncRoot
{
get { return ((ICollection)lst).SyncRoot; }
}
}
And the StateManagedClass
public abstract class StateManagedClass : IStateManager
{
private Boolean isTrackingViewState = default(Boolean);
private StateBag viewState = default(StateBag);
public StateManagedClass()
{
isTrackingViewState = false;
viewState = new StateBag(false);
}
public virtual StateBag ViewState
{
get
{
return viewState;
}
}
public bool IsTrackingViewState
{
get { return isTrackingViewState; }
}
public void LoadViewState(object state)
{
if (state != default(object))
{
((IStateManager)viewState).LoadViewState(state);
}
}
public object SaveViewState()
{
Object savedState = default(Object);
if (viewState != null)
{
savedState =
((IStateManager)viewState).SaveViewState();
}
return savedState;
}
public void TrackViewState()
{
isTrackingViewState = true;
if (viewState != default(StateBag))
{
((IStateManager)viewState).TrackViewState();
}
}
public void SetMarked()
{
viewState.SetDirty(true);
}
}
And the Contact class
public class Contact : StateManagedClass
{
[
Category("Behavior"),
DefaultValue(""),
Description("Name of contact"),
NotifyParentProperty(true)
]
public String Name
{
get
{
Object s = ViewState["Name"];
return (s == null) ? String.Empty : (String)s;
}
set
{
ViewState["Name"] = value;
}
}
[
Category("Behavior"),
DefaultValue(""),
Description("Email address of contact"),
NotifyParentProperty(true)
]
public String Email
{
get
{
Object s = ViewState["Email"];
return (s == null) ? String.Empty : (String)s;
}
set
{
ViewState["Email"] = value;
}
}
[
Category("Behavior"),
DefaultValue(""),
Description("Phone number of contact"),
NotifyParentProperty(true)
]
public String Phone
{
get
{
Object s = ViewState["Phone"];
return (s == null) ? String.Empty : (String)s;
}
set
{
ViewState["Phone"] = value;
}
}
}
Test the control:
<%# Page Title="" Language="C#" MasterPageFile="~/RTL.Master" AutoEventWireup="true" CodeBehind="WebForm15.aspx.cs" Inherits="Controls.WebForm15" %>
<%# Register Assembly="Controls" Namespace="Controls" TagPrefix="cc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="Main" runat="server">
<cc1:QuickContacts ID="QuickContacts1" runat="server" BorderStyle="Solid" BorderWidth="1px">
<cc1:Contact Name="someone" Email="someone#example.com"
Phone="(555) 555-0100" />
<cc1:Contact Name="jae" Email="jae#fourthcoffee.com"
Phone="(555) 555-0101" />
<cc1:Contact Name="lene" Email="lene#contoso.com"
Phone="(555) 555-0102" />
</cc1:QuickContacts>
<br />
<asp:Button runat="server" ID="Button1" Text="Add" OnClick="Button1_Click"></asp:Button>
<asp:Button runat="server" Text="Refresh"></asp:Button>
<br />
<br />
<asp:HyperLink ID="HyperLink1" NavigateUrl="~/WebForm15.aspx"
runat="server">
Reload Page</asp:HyperLink>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="script" runat="server">
</asp:Content>
And the codebehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Controls
{
public partial class WebForm15 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SkolaControlsWorkings.Controls.Contact contact = new SkolaControlsWorkings.Controls.Contact();
contact.Name = "Name";
contact.Email = "Email#mai.com";
contact.Phone = "(111) 111-1111";
QuickContacts1.Contacts.Add(contact);
Button1.Visible = false;
}
}
}
Now you can see how pressing the "Add" button causes new contact item to be added to the list, and how the new added contacts are maintained through page postbacks.
This is should be a complete working example, have fun.
Here is the MSDN original example Web Control Collection Property Example
public ClientApp_Detail GetHomeDetbyClientID_AppID(string clientid, long appId)
{
ClientApp_Detail sp = null;
using (HelpDeskDataContext HDDC = Conn.GetContext())
{
sp = (from st in HDDC.ClientApp_Details where st.ClientID == clientid && st.AppID == Convert.ToInt64(appId) && st.IsDeleted != 1 select st).FirstOrDefault();
}
return sp;
}
For the above .net code i am getting the exception i.e invalid cast exception was unhandled by user code.
but all the values are of exact datatypes i.e. st.ClientID and clientid are varchar(50) and string respectively,AppId ,appid are longint IsDeleted is bit,then what is the cause of error please recommend anything regarding this if any queries i am eager to send the details.
Thank you.
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.ClientApp_Details")]
public partial class ClientApp_Detail : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private string _ClientID;
private long _AppID;
private string _ProjectScope;
private string _ProjectStatus;
private System.DateTime _StrDt;
private System.DateTime _EndDt;
private double _NoofHours;
private long _ID;
private System.Data.Linq.Binary _TimeStamp;
//sumanth edit
private bool _IsDeleted;
private System.Nullable<System.DateTime> _CreationDt;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnClientIDChanging(string value);
partial void OnClientIDChanged();
partial void OnAppIDChanging(long value);
partial void OnAppIDChanged();
partial void OnProjectScopeChanging(string value);
partial void OnProjectScopeChanged();
partial void OnProjectStatusChanging(string value);
partial void OnProjectStatusChanged();
partial void OnStrDtChanging(System.DateTime value);
partial void OnStrDtChanged();
partial void OnEndDtChanging(System.DateTime value);
partial void OnEndDtChanged();
partial void OnNoofHoursChanging(double value);
partial void OnNoofHoursChanged();
partial void OnIDChanging(long value);
partial void OnIDChanged();
partial void OnTimeStampChanging(System.Data.Linq.Binary value);
partial void OnTimeStampChanged();
partial void OnIsDeletedChanging(bool value);
partial void OnIsDeletedChanged();
partial void OnCreationDtChanging(System.Nullable<System.DateTime> value);
partial void OnCreationDtChanged();
#endregion
public ClientApp_Detail()
{
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ClientID", DbType="VarChar(50) NOT NULL", CanBeNull=false, UpdateCheck=UpdateCheck.Never)]
public string ClientID
{
get
{
return this._ClientID;
}
set
{
if ((this._ClientID != value))
{
this.OnClientIDChanging(value);
this.SendPropertyChanging();
this._ClientID = value;
this.SendPropertyChanged("ClientID");
this.OnClientIDChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_AppID", DbType="BigInt NOT NULL", UpdateCheck=UpdateCheck.Never)]
public long AppID
{
get
{
return this._AppID;
}
set
{
if ((this._AppID != value))
{
this.OnAppIDChanging(value);
this.SendPropertyChanging();
this._AppID = value;
this.SendPropertyChanged("AppID");
this.OnAppIDChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ProjectScope", DbType="Text", UpdateCheck=UpdateCheck.Never)]
public string ProjectScope
{
get
{
return this._ProjectScope;
}
set
{
if ((this._ProjectScope != value))
{
this.OnProjectScopeChanging(value);
this.SendPropertyChanging();
this._ProjectScope = value;
this.SendPropertyChanged("ProjectScope");
this.OnProjectScopeChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ProjectStatus", DbType="Text", UpdateCheck=UpdateCheck.Never)]
public string ProjectStatus
{
get
{
return this._ProjectStatus;
}
set
{
if ((this._ProjectStatus != value))
{
this.OnProjectStatusChanging(value);
this.SendPropertyChanging();
this._ProjectStatus = value;
this.SendPropertyChanged("ProjectStatus");
this.OnProjectStatusChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_StrDt", DbType="DateTime NOT NULL", UpdateCheck=UpdateCheck.Never)]
public System.DateTime StrDt
{
get
{
return this._StrDt;
}
set
{
if ((this._StrDt != value))
{
this.OnStrDtChanging(value);
this.SendPropertyChanging();
this._StrDt = value;
this.SendPropertyChanged("StrDt");
this.OnStrDtChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_EndDt", DbType="DateTime NOT NULL", UpdateCheck=UpdateCheck.Never)]
public System.DateTime EndDt
{
get
{
return this._EndDt;
}
set
{
if ((this._EndDt != value))
{
this.OnEndDtChanging(value);
this.SendPropertyChanging();
this._EndDt = value;
this.SendPropertyChanged("EndDt");
this.OnEndDtChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_NoofHours", DbType="Float NOT NULL", UpdateCheck=UpdateCheck.Never)]
public double NoofHours
{
get
{
return this._NoofHours;
}
set
{
if ((this._NoofHours != value))
{
this.OnNoofHoursChanging(value);
this.SendPropertyChanging();
this._NoofHours = value;
this.SendPropertyChanged("NoofHours");
this.OnNoofHoursChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ID", AutoSync=AutoSync.OnInsert, DbType="BigInt NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true, UpdateCheck=UpdateCheck.Never)]
public long ID
{
get
{
return this._ID;
}
set
{
if ((this._ID != value))
{
this.OnIDChanging(value);
this.SendPropertyChanging();
this._ID = value;
this.SendPropertyChanged("ID");
this.OnIDChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_TimeStamp", AutoSync=AutoSync.Always, DbType="rowversion NOT NULL", CanBeNull=false, IsDbGenerated=true, IsVersion=true, UpdateCheck=UpdateCheck.Never)]
public System.Data.Linq.Binary TimeStamp
{
get
{
return this._TimeStamp;
}
set
{
if ((this._TimeStamp != value))
{
this.OnTimeStampChanging(value);
this.SendPropertyChanging();
this._TimeStamp = value;
this.SendPropertyChanged("TimeStamp");
this.OnTimeStampChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_IsDeleted", DbType="Bit NOT NULL", UpdateCheck=UpdateCheck.Never)]
public bool IsDeleted
{
get
{
return this._IsDeleted;
}
set
{
if ((this._IsDeleted != value))
{
this.OnIsDeletedChanging(value);
this.SendPropertyChanging();
this._IsDeleted = value;
this.SendPropertyChanged("IsDeleted");
this.OnIsDeletedChanged();
}
}
}
I have below classes:
public class BusinessFunction
{
private string str_Id;
public string id
{
get { return str_Id; }
set { str_Id = value; }
}
private List<Function> str_FunctionList;
public BusinessFunction() { }
public List<Function> functionList
{
get { return str_FunctionList; }
set { str_FunctionList = value; }
}
}
public class Function
{
private string str_FunctionType;
public string functionType
{
get { return str_FunctionType; }
set { str_FunctionType = value; }
}
private string str_FunctionName;
public string functionName
{
get { return str_FunctionName; }
set { str_FunctionName = value; }
}
private string str_Value;
public string value
{
get { return str_Value; }
set { str_Value = value; }
}
}
I have to bind the above data into Listbox and Listview. The "id" should display in listbox and the "functionList" in listview. When user changes the selection in listbox, it should bring the associated "functionList" into listview.
How to achieve this scenario?
Thanks
Listview Itemsource={Binding functionList} did the trick.
I Have a Base Interface Like this
public interface IHRMISBaseConnector
{
IHRMISEmployeeConnector EmployeeConnector { get ; set; }
}
And i have one more interface like this
public interface IHRMISEmployeeConnector
{
String Add(EmployeeDetails e);
Boolean Update(EmployeeDetails e);
Boolean Delete(int id);
}
I want implement IHRMISBaseConnector in this class DDWEDocumentOperations
How can i implement ? Please let me know if anybody knows it
Something like this should help you:
class FakeImplementationOfEmployeeConnector : IHRMISEmployeeConnector
{
public string Add(EmployeeDetails e)
{
//...
}
public bool Update(EmployeeDetails e)
{
//...
}
public bool Delete(int id)
{
//...
}
}
class DDWEDocumentOperations : IHRMISBaseConnector
{
IHRMISEmployeeConnector employeeConnector = new FakeImplementationOfEmployeeConnector();
public IHRMISEmployeeConnector EmployeeConnector
{
get
{
return employeeConnector;
}
set
{
employeeConnector = value;
}
}
}
Here is an example:
public class DDWEDocumentOperations : IHRMISBaseConnector
{
private IHRMISEmployeeConnector _employeeConnector;
public IHRMISEmployeeConnector EmployeeConnector
{
get { return _employeeConnector; }
set { _employeeConnector = value; }
}
}