How to use two server controls on one page? - asp.net

I have created a server control and calling it on a page two times.
below is the code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
namespace DNWebComponent {
[DefaultProperty("Text")]
[ToolboxData("<{0}:DNdropdown runat=server></{0}:DNdropdown>")]
public class DNdropdown : WebControl, IDNComponent {
private string _label;
private TextBox _txtBox;
public String _ConnectedField;
private string _connectedField;
private string _MultiSeekField;
private List<String> _selectedValue;
private string _InputTable;
private CheckBoxList _Checkbox;
Panel div;
public String ConnectedField {
get { return _connectedField; }
set { _connectedField = value; }
}
public DNdropdown(string label)
: this() {
this._label = label;
}
public String Label {
get { return _label; }
set { _label = value; }
}
public DNdropdown() {
_selectedValue = new List<string>();
_txtBox = new TextBox();
_Checkbox = new CheckBoxList();
div = new Panel();
}
public String InputTable {
get { return _InputTable; }
set { _InputTable = value; }
}
public String MultiSeekField {
get { return _MultiSeekField; }
set { _MultiSeekField = value; }
}
public CheckBoxList AspChekcBoxes {
get { return _Checkbox; }
set { _Checkbox = value; }
}
public List<String> SelectedValue {
get {
foreach (ListItem item in _Checkbox.Items) {
if (item.Selected)
_selectedValue.Add(item.Value);
}
return _selectedValue;
}
set {
if (value != null) {
_selectedValue = value;
}
}
}
public string DivCss { get; set; }
protected List<String> GetPropertyValue<v>(string SelectedValue, List<String> nullValue) {
if (ViewState[SelectedValue] == null) {
return nullValue;
}
return (List<String>)ViewState[SelectedValue];
}
protected override void OnInit(EventArgs e) {
div = new Panel { CssClass = DivCss };
FillControl();
div.Controls.Add(new Literal { Text = Label + ": " });
Panel dvTxtBox = new Panel { CssClass = "dt" };
_txtBox.Text = "Select";
_txtBox.ReadOnly = true;
dvTxtBox.Controls.Add(_txtBox);
Panel dvChkBox = new Panel { CssClass = "divco" };
dvTxtBox.Style.Add("float", "right;");
dvTxtBox.Style.Add("margin-right", "700px;");
dvChkBox.Style.Add("margin-right", "700px;");
dvChkBox.Style.Add("float", "right;");
dvChkBox.Controls.Add(_Checkbox);
div.Controls.Add(dvTxtBox);
div.Controls.Add(dvChkBox);
Controls.Add(div);
}
protected override void RenderContents(HtmlTextWriter output) {
div.RenderControl(output);
}
public bool FillControl() {
_Checkbox.Items.Add("a");
_Checkbox.Items.Add("b");
return true;
}
}
}
<asp:PlaceHolder ID="Place1" runat="server">
<div id="DivDrop" runat="server">
</div>
<div id="divbtn">
<div><cc:DNdropdown ID="dropNew" runat="server" Label="DropDown" />
<cc:DNdropdown ID="newcontrol" runat="server" Label="New Dropdown"/></div>
<div ><asp:Button ID="btnSave" Text="Save" runat="server" OnClick="btnSave_Clicked" /></div> </div>
</asp:PlaceHolder>
I registered this conrol in a Sample.aspx page as above and I am using this control over there.dropNew control is working fine but whenever i add a newcontrol to Sample.aspx page Problem starts.I click on one dropdown second one automatically opens

Related

Using SQLite-net-pcl and can't update the data

So i have this really annoying problem where i Can't seem to get it to update any of the databases i have created, whats worse the i can see the instance is showing the updated information but isn't applying it. I'm really new to this and is my first course project.
This is the code that is being used to update the data:
'''
using Project.Database;
using Project.DataClasses;
using Project.Pages.SuperPages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Essentials;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Project.Pages.UpdateDeleteListItem
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class UpdateDeleteList : ContentPage
{
private new readonly Label Title;
private Style LabelStyle;
private StoreDetails UpdateStoreDetails;
private Entry SNum;
private Entry SName;
private Entry SMName;
private Entry Addy;
public UpdateDeleteList(string pageType, object Item)
{
InitializeComponent();
BindingContext = Item;
UpdateStoreDetails = (StoreDetails)Item;
SetLabelStyle();
string titleMsg = "Update or Delete Selected " + pageType;
Frame frame = new Frame();
Label title = new Label() {Text = titleMsg };
Title = title;
StackLayout titleStack = new StackLayout() { Children = { Title } };
frame.Content = titleStack;
if (pageType == "Store")
{
StoreUDLItem(frame);
}
if (pageType == "Ticket")
{
TicketUDLItem(frame);
}
StylePage();
}
private void SaveButton_Clicked(object sender, EventArgs args)
{
if (StoreCheckValues() == true)
{
var store = SName;
var storeManager = SMName;
var storeNumber = SNum;
var address = Addy;
var storeDataAccess = new StoreDataAccess();
UpdateStoreDetails.StoreName = store.Text;
UpdateStoreDetails.StoreManger = storeManager.Text;
UpdateStoreDetails.StoreNumber = storeNumber.Text;
UpdateStoreDetails.Address = address.Text;
//MerchandiserKey = GetMerchId()
storeDataAccess.SaveStoreDetails(UpdateStoreDetails);
storeDataAccess.SaveAllStoreDetails();
}
'''
here is the data access methods:
'''
using Project.DataClasses;
using SQLite;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using Xamarin.Forms;
namespace Project.Database
{
class StoreDataAccess
{
private SQLiteConnection database;
private static object collisionLock = new object();
public ObservableCollection<StoreDetails> StoreDetails { get; set; }
public StoreDataAccess()
{
database = DependencyService.Get<IDatabaseConnection>().DbConnectionStore();
database.CreateTable<StoreDetails>();
this.StoreDetails = new ObservableCollection<StoreDetails>(database.Table<StoreDetails>());
//AddNewTicket(new Ticket ticket);
}
//add ticket method
public void AddNewStore(StoreDetails item)
{
this.StoreDetails.Add(item);
}
//retrieve ticket method
public StoreDetails GetStoreDetails(int id)
{
lock (collisionLock)
{
return database.Table<StoreDetails>().FirstOrDefault(StoreDetails => StoreDetails.StoreId == id);
}
}
//save ticket
public int SaveStoreDetails(StoreDetails storeDetailsInstance)
{
lock (collisionLock)
{
if (storeDetailsInstance.StoreId != 0)
{
database.Update(storeDetailsInstance);
return storeDetailsInstance.StoreId;
}
else
{
database.Insert(storeDetailsInstance);
return storeDetailsInstance.StoreId;
}
//database.Commit();
}
}
public void SaveAllStoreDetails()
{
lock (collisionLock)
{
foreach (var storeDetailsInstance in this.StoreDetails)
{
if (storeDetailsInstance.StoreId != 0)
{
database.Update(storeDetailsInstance);
}
else
{
database.Insert(storeDetailsInstance);
}
}
}
}
'''
This is the page that is sending the information to the first code block to bind the data too
'''
using Project.Database;
using Project.DataClasses;
using Project.Pages.UpdateDeleteListItem;
using SQLite;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Project.Pages.ListPages
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class StoreList : ContentPage
{
private ObservableCollection<StoreDetails> Items { get; set; }
private readonly StoreDataAccess storeDataAccess;
private readonly SQLiteConnection database;
public StoreList()
{
InitializeComponent();
storeDataAccess = new StoreDataAccess();
this.BindingContext = this.storeDataAccess;
Items = storeDataAccess.StoreDetails;
StoreView.ItemsSource = Items;
}
async void Handle_ItemTapped(object sender, ItemTappedEventArgs e)
{
if (e.Item == null) { return; }
else
{
//var id = Items[e.ItemIndex].StoreId;
await Navigation.PushAsync(new UpdateDeleteList("Store", e.Item));
//Deselect Item
((ListView)sender).SelectedItem = null;
}
}
//page reload handle
protected override void OnAppearing()
{
base.OnAppearing();
var dbName = "StoreListDatabase.db3";
var path = Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.Personal), dbName);
if (database == null)
{
new StoreDataAccess();
}
using (SQLiteConnection conn = new SQLiteConnection(path))
{
Items = storeDataAccess.StoreDetails;
StoreView.ItemsSource = Items;
}
}
}
}
'''
and lastly here is my databbase model for it:
'''
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
using SQLite;
using System.ComponentModel;
namespace Project.DataClasses
{
class StoreDetails : INotifyPropertyChanged
{
private int _storeId;
[PrimaryKey, AutoIncrement, NotNull]
public int StoreId
{
get { return _storeId; }
set { _storeId = value; OnPropertyChanged(nameof(StoreId)); }
}
private string _storeName;
[NotNull, DefaultValue("Enter Store Name")]
public string StoreName
{
get { return _storeName; }
set { _storeName = value; OnPropertyChanged(nameof(_storeName)); }
}
private string _storeManger;
[NotNull, DefaultValue("Enter Store Managers Name")]
public string StoreManger
{
get { return _storeManger; }
set { _storeManger = value; OnPropertyChanged(nameof(StoreManger)); }
}
private string _storeNumber;
[NotNull, DefaultValue("Enter Store Number")]
public string StoreNumber
{
get { return _storeNumber; }
set { _storeNumber = value; OnPropertyChanged(nameof(StoreNumber)); }
}
private string _address;
[NotNull, DefaultValue("Enter Address")]
public string Address
{
get { return _address; }
set { _address = value; OnPropertyChanged(nameof(Address)); }
}
private int _merchandiserKey;
[NotNull]
public int MerchandiserKey
{
get { return _merchandiserKey; }
set { _merchandiserKey = value; OnPropertyChanged(nameof(MerchandiserKey)); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
'''
any help would be greatly appreciated
'''
public int SaveStoreDetails(StoreDetails storeDetailsInstance)
{
lock (collisionLock)
{
if (storeDetailsInstance.StoreId != 0)
{
database.Update(storeDetailsInstance);
return storeDetailsInstance.StoreId;
}
else
{
database.Insert(storeDetailsInstance);
return storeDetailsInstance.StoreId;
}
//database.Commit();
}
}
'''
this is the area where it all seems to be going wrong i just don't know why
Thank You Jason, you were correct in that the error was in calling both the savefunctions and overwriting it!!

ASP.NET maintain control state that has collection items

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

How to access datagrid in View from ViewModel in Silverlight?

Hai i'm doing one silverlight app that uses MVVM architecture.
The Scenario is this. I have one combobox and datagrid in same page.
I have use ObservableCollection to bind the values in Datagrid and in that collection i have three fields namely Fname,Sname and Dept.
I bind Dept in Combobox but if i select any one of department means that value does not update in DataGrid. ie., i have created the code in ViewModel and i use LINQ query and i have Fetched the value also in,
var semp = from s in Employees where s.Dept.Equals(Names.Dept) select s;
i need to send this semp datasource to Datagrid in View.
Datagrid Syntax is :
<my:DataGrid x:Name="McDataGrid" ItemsSource="{Binding Employees,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" Margin="130,151,0,0" Height="137" VerticalAlignment="Top" RowBackground="#AA5D9324" AutoGenerateColumns="True" HorizontalAlignment="Left" Width="196">
</my:DataGrid>
Help me if u Know...
This is the ViewModel Code:
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.ComponentModel;
using Silverlight_MVVM.Model;
using Silverlight_MVVM.Utils;
using System.Linq;
using System.Collections.Generic;
namespace Silverlight_MVVM.ViewModel
{
public class EmployeeListViewModel:INotifyPropertyChanged
{
public ObservableCollection<Employee> Employees { get; private set; }
public EmployeeListViewModel()
{
Employees = Silverlight_MVVM.DataHelper.EmployeeDataHelper.EmployeeData ();
}
private string _fname;
public string Fname
{
get
{
return _fname;
}
set
{
_fname = value;
RaisePropertyChanged("Fname");
}
}
private string _sname;
public string Sname
{
get
{
return _sname;
}
set
{
_sname = value;
RaisePropertyChanged("Sname");
}
}
private string _dept;
public string Dept
{
get
{
return _dept;
}
set
{
_dept = value;
RaisePropertyChanged("Dept");
}
}
private Employee _SelectedEmployee;
public Employee SelectedEmployee
{
get
{
return _SelectedEmployee;
}
set
{
_SelectedEmployee = value;
RaisePropertyChanged("SelectedEmployee");
}
}
private string _demp;
public string demp
{
get
{
return _demp;
}
set
{
_demp = value;
RaisePropertyChanged("demp");
}
}
private Employee _Names;
public Employee Names
{
get
{
return _Names;
}
set
{
_Names = value;
List<Employee> myList = new List<Employee>();
IEnumerable<Employee> myEnumerable = myList;
// List<Employee> listAgain = myEnumerable.ToList();
// Employees = (ObservableCollection<Employee>)Employees.Where(_ => _.Dept.Equals(Names.Dept));
RaisePropertyChanged("Names");
}
}
public void HandleShowMessage()
{
// MessageBox.Show("Hello " + Names + ",Welcome to EventTrigger for MVVM.");
}
public RelayCommand _AddEmployeeCommand;
/// <summary>
/// Returns a command that show the customer.
/// </summary>
public ICommand AddEmployeeCommand
{
get
{
if (_AddEmployeeCommand == null)
{
_AddEmployeeCommand = new RelayCommand(
param => this.AddEmployee(),
param => this.CanAddEmployee
);
}
return _AddEmployeeCommand;
}
}
public bool CanAddEmployee
{
get
{
return true;
}
}
public void AddEmployee()
{
Employee newEmployee = new Employee();
if (Names == null)
{
newEmployee.Fname = this.Fname;
newEmployee.Sname = this.Sname;
newEmployee.Dept = this.Dept;
Employees.Add(newEmployee);
//SelectedEmployee = newEmployee.ToString();
}
else //This is the event for getting selected item through combobox and the linq query fetching
{
Employees = Silverlight_MVVM.DataHelper.EmployeeDataHelper.EmployeeData();
var semp = from emp in Employees where emp.Dept.Equals(Names.Dept) select emp;
}
}
#region INotifyPropertyChanged
// [field: NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}

How to solve postback in custom sever controls?

I am creating custom server controls.I created a textbox in this used this control in my page.But when page is posted back(postback) the value of textbox gets omitted..I thought of using viewstate here but m nt getting textbox value .May be m using in wrong way help me plz
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Reflection;
namespace DNWebComponent {
[DefaultProperty("Text")]
[ToolboxData("<{0}:DNTextBox runat=server></{0}:DNTextBox>")]
public class DNTextBox : WebControl, IDNComponent {
public String _ConnectedField;
private string _label;
private TextBox _txtBox;
private string _connectedField;
private string _MultiSeekField;
private string _InputTable;
public string ControlClientID;
public DNTextBox() {
_txtBox = new TextBox();
}
[PersistToViewState]
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string Text {
get {
String s = (String)ViewState["Text"];
return ((s == null) ? "[" + AspTextBox.Text + "]" : s);
}
set {
ViewState["Text"] = value;
}
}
public DNTextBox(string label)
: this() {
this._label = label;
}
public String Label {
get { return _label; }
set { _label = value; }
}
public String ConnectedField {
get { return _connectedField; }
set { _connectedField = value; }
}
public String MultiSeekField {
get { return _MultiSeekField; }
set { _MultiSeekField = value; }
}
public String InputTable {
get { return _InputTable; }
set { _InputTable = value; }
}
public TextBox AspTextBox {
get { return _txtBox; }
set { _txtBox = value; }
}
public string DivCss { get; set; }
protected override void RenderContents(HtmlTextWriter output) {
output.Write("<div class=\"" + DivCss + "\" >");
output.Write(Text);
output.Write(_label + ": ");
_txtBox.RenderControl(output);
output.Write("</div>");
}
public bool FillControl() {
return false;
}
protected override void LoadViewState(object savedState) {
base.LoadViewState(savedState);
PropertyInfo[] properties = GetType().GetProperties();
foreach (PropertyInfo property in properties) {
object[] attributes = property.GetCustomAttributes(typeof(PersistToViewState), true);
if (attributes.Length > 0) {
if (ViewState[property.Name] != null)
property.SetValue(this, ViewState[property.Name], null);
}
}
}
protected override object SaveViewState() {
ViewState["Text"] = AspTextBox.Text;
//PropertyInfo[] properties = GetType().GetProperties();
//foreach (PropertyInfo property in properties) {
// object[] attributes = property.GetCustomAttributes(typeof(PersistToViewState), true);
// if (attributes.Length > 0)
// ViewState[property.Name] = property.GetValue(this, null);
//}
return base.SaveViewState();
}
[AttributeUsage(AttributeTargets.Property)]
public class PersistToViewState : Attribute {
}
}
}
This is another way to achieve what you are trying to do that will handle all the events and viewstate information:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Reflection;
namespace DNWebComponent {
[DefaultProperty("Text")]
[ToolboxData("<{0}:DNTextBox runat=server></{0}:DNTextBox>")]
public class DNTextBox : WebControl, IDNComponent {
public String _ConnectedField;
private string _label;
private TextBox _txtBox;
private string _connectedField;
private string _MultiSeekField;
private string _InputTable;
public string ControlClientID;
public DNTextBox() {
_txtBox = new TextBox();
}
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string Text {
get {
String s = (String)ViewState["Text"];
return ((s == null) ? "[" + AspTextBox.Text + "]" : s);
}
set {
ViewState["Text"] = value;
}
}
public DNTextBox(string label)
: this() {
this._label = label;
}
public String Label {
get { return _label; }
set { _label = value; }
}
public String ConnectedField {
get { return _connectedField; }
set { _connectedField = value; }
}
public String MultiSeekField {
get { return _MultiSeekField; }
set { _MultiSeekField = value; }
}
public String InputTable {
get { return _InputTable; }
set { _InputTable = value; }
}
public TextBox AspTextBox {
get { return _txtBox; }
set { _txtBox = value; }
}
public string DivCss { get; set; }
protected override void OnInit(EventArgs e) {
var div = new Panel{ CssClass = DivCss };
div.Controls.Add(new Literal{ Text = Text });
div.Controls.Add(new Literal{ Text = _label + ":" });
div.Controls.Add(_txtBox);
Controls.Add(div);
}
public bool FillControl() {
return false;
}
}
}
This is happening because you have not added the child text box control to your control - because the text-box is not part of control tree, it will not retain its value (or other properties).
You should derive from CompositeControl (or develop UserControl) instead. For example,
...
public class DNTextBox : CompositeControl, IDNComponent {
private TextBox _txtBox;
protected override void CreateChildControls()
{
_txtBox = new TextBox();
_txtBox.ID = "T";
this.Controls.Add(_textBox);
}
public TextBox AspTextBox
{
get { EnsureChildControls(); return _txtBox; }
}
protected override void RenderContents(HtmlTextWriter output)
{
output.Write("<div class=\"" + DivCss + "\" >");
output.Write(Text);
output.Write(_label + ": ");
base.RenderContents(output); // this will create html for child controls
output.Write("</div>");
}
}
Disclaimer: illustrative code, not tested
Whenever, you need to refer to the text-box, make sure that you call EnsureChildControls as shown in AspTextBox property.
This code worked for me.I added a method add attribute
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace DNWebComponent {
[DefaultProperty("Text")]
[ToolboxData("<{0}:DNTextBox runat=server></{0}:DNTextBox>")]
public class DNTextBox : TextBox, IDNComponent {
public String _ConnectedField;
private string _label;
private TextBox _txtBox;
private string _connectedField;
private string _MultiSeekField;
private string _InputTable;
public string ControlClientID;
public DNTextBox() {
_txtBox = this;
}
public DNTextBox(string label)
: this() {
this._label = label;
}
public String Label {
get { return _label; }
set { _label = value; }
}
public String ConnectedField {
get { return _connectedField; }
set { _connectedField = value; }
}
public String MultiSeekField {
get { return _MultiSeekField; }
set { _MultiSeekField = value; }
}
public String InputTable {
get { return _InputTable; }
set { _InputTable = value; }
}
public TextBox AspTextBox {
get { return this; }
set { _txtBox = value; }
}
public string DivCss { get; set; }
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand,
Name = "FullTrust")]
protected override void AddAttributesToRender(HtmlTextWriter writer) {
writer.AddAttribute("Label", Label);
writer.AddAttribute("Text", Text);
base.AddAttributesToRender(writer);
}
protected override void RenderContents(HtmlTextWriter output) {
output.Write("<div class=\"" + DivCss + "\" >");
output.Write(_label + ": ");
output.Write("</div>");
}
public bool FillControl() {
return false;
}
}
}

Finding Controls in an ITemplated Custom Control

I have created a custom server control with properties implementing the ITemplate interface. It is basically a custom panel box with a header, body & footer. Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace ACME.Web.Controls
{
[ParseChildren(true)]
[DefaultProperty("Text")]
[ToolboxData("")]
public class Panel : WebControl, INamingContainer
{
private ITemplate _header = null;
private Control _headerControl = null;
private Control _headerContainerControl = null;
private ITemplate _content = null;
private Control _contentControl = null;
private Control _contentContainerControl = null;
private ITemplate _footer = null;
private Control _footerControl = null;
private Control _footerContainerControl = null;
[PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(TemplateControl)),
TemplateInstance(TemplateInstance.Single)]
public ITemplate Header
{
get { return _header; }
set { _header = value; }
}
[PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(TemplateControl)),
TemplateInstance(TemplateInstance.Single)]
public ITemplate Content
{
get { return _content; }
set { _content = value; }
}
[PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(TemplateControl)),
TemplateInstance(TemplateInstance.Single)]
public ITemplate Footer
{
get { return _footer; }
set { _footer = value; }
}
protected override void CreateChildControls()
{
Controls.Clear();
if (this.ID == null) this.ID = "panel-" + Guid.NewGuid().ToString();
this.CssClass = "panel";
if (this.Header == null)
{
this.CssClass += " without-header";
}
else
{
this.CssClass += " with-header";
_headerControl = new System.Web.UI.WebControls.Panel { CssClass = "panel-header" };
_headerControl.Controls.Add(new System.Web.UI.WebControls.Panel { CssClass = "panel-header-l" });
_headerControl.Controls.Add(new System.Web.UI.WebControls.Panel { CssClass = "panel-header-c" });
_headerControl.Controls.Add(new System.Web.UI.WebControls.Panel { CssClass = "panel-header-r" });
_headerControl.Controls[1].Controls.Add(new System.Web.UI.WebControls.Panel { CssClass = "panel-header-wrapper" });
_headerControl.Controls[1].Controls[0].Controls.Add(new System.Web.UI.WebControls.Panel { CssClass = "wrapper" });
_headerContainerControl = new Control();
if (this.Header != null)
{
Header.InstantiateIn(_headerContainerControl);
}
else
{
_headerContainerControl.Controls.Add(new LiteralControl("Test"));
}
_headerControl.Controls[1].Controls[0].Controls[0].Controls.Add(_headerContainerControl);
Controls.Add(_headerControl);
}
_contentControl = new System.Web.UI.WebControls.Panel { CssClass = "panel-body" };
_contentControl.Controls.Add(new System.Web.UI.WebControls.Panel { CssClass = "panel-body-t" });
_contentControl.Controls[0].Controls.Add(new System.Web.UI.WebControls.Panel { CssClass = "panel-body-t-l" });
_contentControl.Controls[0].Controls.Add(new System.Web.UI.WebControls.Panel { CssClass = "panel-body-t-c" });
_contentControl.Controls[0].Controls.Add(new System.Web.UI.WebControls.Panel { CssClass = "panel-body-t-r" });
_contentControl.Controls.Add(new System.Web.UI.WebControls.Panel { CssClass = "panel-body-m" });
_contentControl.Controls[1].Controls.Add(new System.Web.UI.WebControls.Panel { CssClass = "panel-body-m-l" });
_contentControl.Controls[1].Controls.Add(new System.Web.UI.WebControls.Panel { CssClass = "panel-body-m-c" });
_contentControl.Controls[1].Controls.Add(new System.Web.UI.WebControls.Panel { CssClass = "panel-body-m-r" });
_contentControl.Controls[1].Controls[1].Controls.Add(new System.Web.UI.WebControls.Panel { CssClass = "panel-body-wrapper" });
_contentControl.Controls[1].Controls[1].Controls[0].Controls.Add(new System.Web.UI.WebControls.Panel { CssClass = "scroll-wrapper" });
_contentControl.Controls.Add(new System.Web.UI.WebControls.Panel { CssClass = "panel-body-b" });
_contentControl.Controls[2].Controls.Add(new System.Web.UI.WebControls.Panel { CssClass = "panel-body-b-l" });
_contentControl.Controls[2].Controls.Add(new System.Web.UI.WebControls.Panel { CssClass = "panel-body-b-c" });
_contentControl.Controls[2].Controls.Add(new System.Web.UI.WebControls.Panel { CssClass = "panel-body-b-r" });
_contentContainerControl = new Control();
if (this.Content != null)
{
Content.InstantiateIn(_contentContainerControl);
}
else
{
_contentContainerControl.Controls.Add(new LiteralControl("Test"));
}
_contentControl.Controls[1].Controls[1].Controls[0].Controls[0].Controls.Add(_contentContainerControl);
Controls.Add(_contentControl);
if (this.Footer == null)
{
this.CssClass += " without-footer";
}
else
{
this.CssClass += " with-footer";
_footerControl = new System.Web.UI.WebControls.Panel { CssClass = "panel-footer" };
_footerContainerControl = new Control();
if (this.Footer != null)
{
Footer.InstantiateIn(_footerContainerControl);
}
else
{
_footerContainerControl.Controls.Add(new LiteralControl("Test"));
}
_footerControl.Controls.Add(_footerContainerControl);
Controls.Add(_footerControl);
}
}
protected override HtmlTextWriterTag TagKey
{
get { return HtmlTextWriterTag.Div; }
}
}
}
It works perfectly but one cannot really access controls within the ITemplates from the code behind. I would like to be able to add and remove controls from the ITemplate regions of my custom control. What would be the best way to do this?
you can try container.findcontrol("")

Resources