How to solve postback in custom sever controls? - asp.net

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;
}
}
}

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!!

Switch Toggling Event Using MVVM

I realized recently that a switch doesn't have a command. And i need to bind the toggling event to my view model. How do i go about it?
I tried to bind the command to Toggled event but the code is running into error
You can use EventToCommandBehavior to convert the event to command
create the EventToCommandBehavior class
using System;
using Xamarin.Forms;
namespace xxx
{
public class BehaviorBase<T> : Behavior<T> where T : BindableObject
{
public T AssociatedObject { get; private set; }
protected override void OnAttachedTo(T bindable)
{
base.OnAttachedTo(bindable);
AssociatedObject = bindable;
if (bindable.BindingContext != null)
{
BindingContext = bindable.BindingContext;
}
bindable.BindingContextChanged += OnBindingContextChanged;
}
protected override void OnDetachingFrom(T bindable)
{
base.OnDetachingFrom(bindable);
bindable.BindingContextChanged -= OnBindingContextChanged;
AssociatedObject = null;
}
void OnBindingContextChanged(object sender, EventArgs e)
{
OnBindingContextChanged();
}
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
BindingContext = AssociatedObject.BindingContext;
}
}
}
using System;
using System.Reflection;
using System.Windows.Input;
using Xamarin.Forms;
namespace xxx
{
public class EventToCommandBehavior : BehaviorBase<View>
{
Delegate eventHandler;
public static readonly BindableProperty EventNameProperty = BindableProperty.Create("EventName", typeof(string), typeof(EventToCommandBehavior), null, propertyChanged: OnEventNameChanged);
public static readonly BindableProperty CommandProperty = BindableProperty.Create("Command", typeof(ICommand), typeof(EventToCommandBehavior), null);
public static readonly BindableProperty CommandParameterProperty = BindableProperty.Create("CommandParameter", typeof(object), typeof(EventToCommandBehavior), null);
public static readonly BindableProperty InputConverterProperty = BindableProperty.Create("Converter", typeof(IValueConverter), typeof(EventToCommandBehavior), null);
public string EventName
{
get { return (string)GetValue(EventNameProperty); }
set { SetValue(EventNameProperty, value); }
}
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
public object CommandParameter
{
get { return GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
public IValueConverter Converter
{
get { return (IValueConverter)GetValue(InputConverterProperty); }
set { SetValue(InputConverterProperty, value); }
}
protected override void OnAttachedTo(View bindable)
{
base.OnAttachedTo(bindable);
RegisterEvent(EventName);
}
protected override void OnDetachingFrom(View bindable)
{
DeregisterEvent(EventName);
base.OnDetachingFrom(bindable);
}
void RegisterEvent(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return;
}
EventInfo eventInfo = AssociatedObject.GetType().GetRuntimeEvent(name);
if (eventInfo == null)
{
throw new ArgumentException(string.Format("EventToCommandBehavior: Can't register the '{0}' event.", EventName));
}
MethodInfo methodInfo = typeof(EventToCommandBehavior).GetTypeInfo().GetDeclaredMethod("OnEvent");
eventHandler = methodInfo.CreateDelegate(eventInfo.EventHandlerType, this);
eventInfo.AddEventHandler(AssociatedObject, eventHandler);
}
void DeregisterEvent(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return;
}
if (eventHandler == null)
{
return;
}
EventInfo eventInfo = AssociatedObject.GetType().GetRuntimeEvent(name);
if (eventInfo == null)
{
throw new ArgumentException(string.Format("EventToCommandBehavior: Can't de-register the '{0}' event.", EventName));
}
eventInfo.RemoveEventHandler(AssociatedObject, eventHandler);
eventHandler = null;
}
void OnEvent(object sender, object eventArgs)
{
if (Command == null)
{
return;
}
object resolvedParameter;
if (CommandParameter != null)
{
resolvedParameter = CommandParameter;
}
else if (Converter != null)
{
resolvedParameter = Converter.Convert(eventArgs, typeof(object), null, null);
}
else
{
resolvedParameter = eventArgs;
}
if (Command.CanExecute(resolvedParameter))
{
Command.Execute(resolvedParameter);
}
}
static void OnEventNameChanged(BindableObject bindable, object oldValue, object newValue)
{
var behavior = (EventToCommandBehavior)bindable;
if (behavior.AssociatedObject == null)
{
return;
}
string oldEventName = (string)oldValue;
string newEventName = (string)newValue;
behavior.DeregisterEvent(oldEventName);
behavior.RegisterEvent(newEventName);
}
}
}
in your xaml
<Switch >
<Switch.Behaviors>
<local:EventToCommandBehavior EventName="Toggled" Command="{Binding ToggledCommand}"/>
</Switch.Behaviors>
</Switch>
And in your ViewModel
public class MyViewModel
{
public ICommand ToggledCommand { get; private set; }
public MyViewModel()
{
ToggledCommand = new Command(() => {
// do some thing you want
});
}
}
I bind a bool property on my viewmodel to the IsToggled property on the switch, then handle when this changes in the viewmodel.

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 use two server controls on one page?

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

help with image class implementation

i build that class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
namespace CDN
{
public class Image
{
#region Image parameters
private int _PG_ID;
private string _PG_FileName;
private int _PG_ItemId;
private int _TD_ID;
private Boolean _PG_Visible;
private string _PG_Caption;
public int PG_ID
{
get { return _PG_ID; }
set { _PG_ID = value; }
}
public string PG_FileName
{
get { return _PG_FileName; }
set { _PG_FileName = value; }
}
public int PG_ItemId
{
get { return _PG_ItemId; }
set { _PG_ItemId = value; }
}
public int TD_ID
{
get { return _TD_ID; }
set { _TD_ID = value; }
}
public Boolean PG_Visible
{
get { return _PG_Visible; }
set { _PG_Visible = value; }
}
public string PG_Caption
{
get { return _PG_Caption; }
set { _PG_Caption = value; }
}
#endregion
public Image(int PG_ID)
{
GetImage(PG_ID);
}
public Image()
{
}
private void GetImage(int PG_ID)
{
//TODO get image data from db and fill all parameters with the data
}
public int SaveImage(FileUpload fileUpload,string caption,Boolean visible,int toolId,int itemId)
{
try
{
SaveImageToTemporaryFolder(fileUpload);
return CreateImageOnDb(fileUpload.FileName, caption, visible, toolId, itemId);
}
catch (Exception)
{
throw;
}
}
private int CreateImageOnDb(string fileName, string caption, bool visible, int toolId, int itemId)
{
//TODO save image data on db return image id
return 0;
}
private void SaveImageToTemporaryFolder(FileUpload fileUpload)
{
try
{
string savePath = HttpContext.Current.Server.MapPath("~") + "\\upload\\pgallery\\";
fileUpload.SaveAs(savePath + fileUpload.FileName);
}
catch (Exception)
{
throw;
}
}
}
}
How to pass the file?
EDITED:
in the function SaveImage i pass a FileUpload control.
I want to use the class like this:
when uploading image to craete a new Image object and to pass him all data, but how can i transfer him the file.
Image img = new Image();
img.PG_Caption = "my file name";
img.PG_Visible = True;
img.SaveImage(file);
You can alter your SaveImage function to take a Stream and pass in like this:
using (MemoryStream stream = new MemoryStream(fileUpload.FileBytes))
{
img.SaveImage(stream);
}

Resources