Problem
Problem only comes when I try to insert. However I could browse through records. When I insert a new record, the UserControl does not consider the value I typed in, instead it stores as null. I basically think on New record, it does not sync.
The Form Layout
Purpose of UserControl
The DB stores Field value in the form of JKB-932340094VN00 where I use my UserControl for split Values by - and display it in 2 TextBox in it. So one TextBox will have the Value of JKB and other will have 932340094VN00
UserControl is as follows:
public partial class ucClientAccountIDParser : UserControl, INotifyPropertyChanged
{
public ucClientAccountIDParser()
{
InitializeComponent();
id = "JKB-821230063VN00";
txtClientAccountID.TextChanged += new EventHandler(clientaccountIDChanged);
txtCustodyID.TextChanged += new EventHandler(custodyIDChanged);
}
private string _clientaccountID = string.Empty;
public string ClientaccountID
{
get { return _clientaccountID; }
set
{
_clientaccountID = value;
txtClientAccountID.Text = this._clientaccountID;
}
}
private string _custodyID = string.Empty;
public string CustodyID
{
get { return _custodyID; }
set
{
_custodyID = value;
txtCustodyID.Text = this._custodyID;
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
public string id = string.Empty;
[System.ComponentModel.Bindable(true)]
public string Text
{
get
{
return id;
}
set
{
id = value;
if (id != null)
{
string[] aVal = id.Split('-');
if (aVal.Length > 1)
{
this.CustodyID = aVal[0];
this.ClientaccountID = aVal[1];
}
else
{
this.ClientaccountID = id;
}
}
else
{
this.CustodyID = string.Empty;
this.ClientaccountID = string.Empty;
}
NotifyPropertyChanged(id);
}
}
public void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Text"));
}
}
private void clientaccountIDChanged(object sender, EventArgs e)
{
this.id = string.Format("{0}-{1}", txtCustodyID.Text, (sender as TextBox).Text);
NotifyPropertyChanged(this.id);
}
private void custodyIDChanged(object sender, EventArgs e)
{
this.id = string.Format("{0}-{1}", (sender as TextBox).Text, txtClientAccountID.Text);
NotifyPropertyChanged(this.id);
}
}
This is how I bind it:
try
{
this.Init(null);
this.Text = "General Account Add/Change";
objTable = new ClientAccountBusinessTable();
this.PrimaryDataAdapters = new ClientAccountBusinessTable[1] { objTable };
this.PrimaryDataGridView = null;
objTable.KeyDBField = "CLIENTID";
PrimaryBindingSource = new BindingSource[1] { bindingSource1 };
PrimaryDataSet.Tables.Add(objTable.GetBusinessTable());
SetKeyDBControl(new Control[1] { ucClientAccountIDParser1 }, new string[1] { "CLIENTID" });
ucClientAccountIDParser1.DataBindings.Clear();
ucClientAccountIDParser1.DataBindings.Add(new Binding("Text", this.bindingSource1, "CLIENTID"));
bindingSource1.DataMember = this.PrimaryDataSet.Tables[0].TableName;
bindingSource1.DataSource = this.PrimaryDataSet;
}
catch (Exception ex)
{
objTable = null;
throw ex;
}
I cant figure out why it takes null. Let me know if I carried out design of UserControl in proper way.
I hope anybody can help me out.
Related
I've got a class of users with some properties like name, age, gender and message
and so I have a form that in it some text boxes created dynamically for each property of each user and I bind each textbox to appropriate properties.
When the users connect to my program and change their properties the text boxes don't change.
This is my user class:
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace binding_network
{
class user : INotifyPropertyChanged
{
private string _name;
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
NotifyPropertyChanged();
}
}
}
private int _age;
public int Age
{
get { return _age; }
set
{
if (_age != value)
{
_age = value;
NotifyPropertyChanged();
}
}
}
private string _message;
public string Message
{
get { return _message; }
set
{
if (_message != value)
{
_message = value;
NotifyPropertyChanged();
}
}
}
private string _gender;
public string Gender
{
get { return _gender; }
set
{
if (true)
{
_gender = value;
NotifyPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
and this is my form code:
public partial class Form1 : Form
{
private BindingSource userBindingSource = new BindingSource();
BindingList<user> userList = new BindingList<user>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
///some code to create textboxes dynamically....
txtName.DataBindings.Clear();
txtName.DataBindings.Add("text", userBindingSource[userIndex], "name");
txtAge.DataBindings.Clear();
txtAge.DataBindings.Add("text", userBindingSource[userIndex], "age");
txtGender.DataBindings.Clear();
txtGender.DataBindings.Add("text", userBindingSource[userIndex], "gender");
txtMessage.DataBindings.Clear();
txtMessage.DataBindings.Add("text", userBindingSource[userIndex], "message");
}
}
And by this method, I receive the data by network
private void GetMessage(object obj)
{
user user1 = (user)obj;
try
{
while (true)
{
byte[] buffer = new byte[1024];
int rec = user1.SocketClient.Receive(buffer, 0, buffer.Length, 0);
Array.Resize(ref buffer, rec);
if (rec > 0)
{
user1.Name = BitConverter.ToString(buffer, 0);
user1.Gender = BitConverter.ToString(buffer, 80);
user1.Age = BitConverter.ToInt32(buffer, 96);
user1.Message = BitConverter.ToString(buffer, 160);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
But after receiving the data the textboxes don't refresh
A lot of code appears to be missing, but here's a few things...
The userBindingSource hasn't been connected to userList.
The binding propertyName and dataMember parameters have incorrect casing.
The userIndex isn't defined.
Even if it were, binding to userBindingSource[userIndex] doesn't allow navigation of the source (maybe you're fine with that).
So let's fix those:
public partial class Form1 : Form
{
private BindingSource userBindingSource = new BindingSource();
BindingList<user> userList = new BindingList<user>();
int userIndex = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
userBindingSource.DataSource = userList;
userIndex = userBindingSource.Position;
///some code to create textboxes dynamically....
txtName.DataBindings.Clear();
txtName.DataBindings.Add("Text", userBindingSource, "Name");
txtAge.DataBindings.Clear();
txtAge.DataBindings.Add("Text", userBindingSource, "Age");
txtGender.DataBindings.Clear();
txtGender.DataBindings.Add("Text", userBindingSource, "Gender");
txtMessage.DataBindings.Clear();
txtMessage.DataBindings.Add("Text", userBindingSource, "Message");
}
}
Assuming that userList has been populated, you may now navigate the userBindingSource like this:
// However you're tracking userIndex, or maybe...
// userIndex = userList.IndexOf(user1);
userBindingSource.Position = userIndex;
Or any of these:
userBindingSource.MoveFirst();
userBindingSource.MovePrevious();
userBindingSource.MoveNext();
userBindingSource.MoveLast();
And finally, remove the infinite while (true) loop in GetMessage.
At this point, if your data is correctly received and parsed, your TextBox controls should update.
Edit...
So you're multi-threading this, which is great.
Now we have to make sure all operations that result in a UI change are done on the proper thread.
Lets do this (assuming GetMessage is defined inside the Form class):
if (rec > 0)
{
var name = BitConverter.ToString(buffer, 0);
var gender = BitConverter.ToString(buffer, 80);
var age = BitConverter.ToInt32(buffer, 96);
var message = BitConverter.ToString(buffer, 160);
this.Invoke(new Action(() =>
{
user1.Name = name;
user1.Gender = gender;
user1.Age = age;
user1.Message = message;
}));
}
And this:
catch (Exception ex)
{
this.Invoke(new Action(() => MessageBox.Show(ex.ToString())));
}
And binding source navigation (if on a different thread):
this.Invoke(new Action(() => userBindingSource.Position = userIndex));
You may also look into using the BeginInvoke method.
I am trying to bind a list of strings to the contents of a list box. For some reason, I get results for bluetape list, but the contents of BluetapeList does not ever make it into the listbox. Any help would be much appreciated!
XAML:
<ListBox
Name="lbxTapeIn"
Grid.Row="1"
Grid.Column="1"
Grid.ColumnSpan="1"
Width="70"
Height="80"
SelectionChanged="TapeSelectionChanged"
ItemsSource="{Binding}"
SelectedValue="{Binding SelectedBt}"
Background="DeepSkyBlue"
Foreground="MidnightBlue"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Margin="5"/>
Code Behind:
public partial class OverrideAoiBinningWindow : Window
{
private OverrideAoiBinningWindowViewModel ovAoiBinWin;
public OverrideAoiBinningWindow()
{
InitializeComponent();
ovAoiBinWin = new OverrideAoiBinningWindowViewModel(tvwWaferList, txtFilter);
AssignDataContexts();
}
private void AssignDataContexts()
{
btnChooseWafer.DataContext = ovAoiBinWin;
btnSave.DataContext = ovAoiBinWin;
txtWafer.DataContext = ovAoiBinWin;
cbxAoiState.DataContext = ovAoiBinWin;
lbxTapeIn.DataContext = ovAoiBinWin.BluetapeList;
}
private void TapeSelectionChanged(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrEmpty(ovAoiBinWin.SelectedWafer))
{
if (cbxAoiState.SelectedValue != null)
{
btnSave.IsEnabled = true;
}
}
}
private void AoiStateChanged(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrEmpty(ovAoiBinWin.SelectedWafer))
{
if (lbxTapeIn.SelectedValue != null)
{
btnSave.IsEnabled = true;
}
}
}
private void Close(object sender, RoutedEventArgs e)
{
this.Close();
}
}
View Model:
public class OverrideAoiBinningWindowViewModel : ViewModelBase, ISelectWafers
{
public OverrideAoiBinningWindowViewModel(TreeView tvwWaferList, TextBox txtFilter)
{
// Set private fields
this.tvwWaferList = tvwWaferList;
this.txtFilter = txtFilter;
// Instantiate objects and initialize settings
this.InstantiateObjects();
this.SetControlSettings();
// Run the initialization thread
initThread.RunWorkerAsync();
}
public string SelectedWafer
{
get
{
return selectedWafer;
}
set
{
selectedWafer = value;
OnPropertyChanged("SelectedWafer");
}
}
public string SelectedBt
{
get
{
return selectedBt;
}
set
{
selectedBt = value;
OnPropertyChanged("SelectedBt");
}
}
public string SelectedAoiState
{
get
{
return selectedAoiState;
}
set
{
selectedAoiState = value;
OnPropertyChanged("SelectedAoiState");
}
}
public List<string> AOIStateList
{
get
{
return aoiStateList;
}
set
{
aoiStateList = value;
OnPropertyChanged("AOIStateList");
}
}
public List<string> BluetapeList
{
get
{
return bluetapeList;
}
set
{
bluetapeList = value;
OnPropertyChanged("BluetapeList");
}
}
public ICommand SelectWaferCommand
{
get
{
if (selectWaferCommand == null)
{
selectWaferCommand = new DelegateCommand(SelectWafer);
}
return selectWaferCommand;
}
}
public ICommand SaveAoiStateCommand
{
get
{
if (saveAoiStateCommand == null)
{
saveAoiStateCommand = new DelegateCommand(SaveAoiState);
}
return saveAoiStateCommand;
}
}
private void InstantiateObjects()
{
initThread = new BackgroundWorker();
aoiStateList = new List<string>();
bluetapeList = new List<string>();
converter = new WaferIDConverter();
}
private void SetControlSettings()
{
initThread.WorkerReportsProgress = false;
initThread.WorkerSupportsCancellation = false;
initThread.DoWork += InitThread_DoWork;
initThread.RunWorkerCompleted += InitThread_RunWorkerCompleted;
}
private void PopulateAoiStateList()
{
aoiStateList.Add("True");
aoiStateList.Add("False");
aoiStateList.Add("NotBinned");
aoiStateList.Add("NeverAOI");
}
private void PopulateBluetapeList()
{
waferQueries = new WaferQueries(
DataLibrary.GetSingulationOne(selectedWafer));
foreach (BlueTape tape in waferQueries.GetBlueTapeList())
{
bluetapeList.Add(tape.Name);
}
OnPropertyChanged("BluetapeList");
}
private void SaveAoiState()
{
Mouse.OverrideCursor = Cursors.Wait;
singOne = new SingOneTable();
singOne.OverrideAoiState(selectedWafer, selectedBt, selectedAoiState);
Mouse.OverrideCursor = null;
MessageBox.Show(
"The AOI state of " + selectedBt + " from " + selectedWafer +
" has been successfully changed to " + selectedAoiState + "!",
"AOI State Saved", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
public void SelectWafer()
{
Mouse.OverrideCursor = Cursors.Wait;
SelectedWafer = tvwWaferList.SelectedValue.ToString();
PopulateBluetapeList();
Mouse.OverrideCursor = null;
}
private void InitThread_DoWork(object sender, DoWorkEventArgs e)
{
if (!handled)
{
PopulateAoiStateList();
tvwPresenter = new TreeViewPresenter(tvwWaferList, txtFilter, this);
tvwPresenter.WaferList = DataLibrary.GetWaferList();
handled = true;
}
}
private void InitThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
tvwPresenter.TreeView.DataContext = tvwPresenter.ProcessesAndWafers;
tvwPresenter.WaferListCache = tvwPresenter.ProcessesAndWafers;
tvwPresenter.ProcessArray = tvwPresenter.WaferListCache.ToArray();
//TODO: Update Status text block
}
}
Answered (2nd comment) by Dilshod:
The fix was to change my List to ObservableCollection.
Once I made that change, everything worked as expected; thanks Dilshod!
Binding WPF Drop-Down control dynamically (C#).
I am using the following simple solution for binding WPF drop-down (combo-box) to a Dictionary object programmatically (C#). In this particular example Dictionary contains the list of Countries with corresponding 2-digit Country Codes (keys):
Listing 1. Dictionary object contains list of Countries w/2-digit Country codes
Dictionary<string, string> _co = new Dictionary<string, string>();
_co.Add(String.Empty, String.Empty);
_co.Add("US", "United States");
_co.Add("CA", "Canada");
_co.Add("MX", "Mexico");
Listing 2. Binding Drop-down to Dictionary object (WPF/C#)
// binding to country list Dictionary object (_co)
_cmbCountry.ItemsSource = _co;
// Country 2-digit Code used as a key
_cmbCountry.SelectedValuePath = _dKey;
// Country Name (string to display)
_cmbCountry.DisplayMemberPath = _dValue;
// first index selected
_cmbCountry.SelectedIndex = 0;
// DropDownClosed event subscription using Lambda notation
_cmbCountry.DropDownClosed += (s, e) => ComboBox_Closed(s, e);
The code snippet above (Listing 2.) also shows how to subscribe to the control event using 'short-cut' Lambda style. Hope this will help. Regards, AB
PS. You can also find more information on Drop-Down control binding techniques in my article: Binding DropDownList to various data structures in Microsoft ASP.NET
I have a class with INotifyPropertyChanged interface. There is a property with the name Total Progress.
I have a Form with Progress Bar on it. I want to send the TotalProgress property changed notifications to this Progress Bar and set it's value.
Do I need to catch the PropertyChangedEvent in the Form also?
Edit: WPF Form Code
using System.ComponentModel;
using System.Windows;
using System.Windows.Data;
using System;
using System.Windows.Threading;
namespace SUpdater
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
BackgroundWorker bw = new BackgroundWorker();
DownloadFile FileDownloadClass = new DownloadFile();
public MainWindow()
{
InitializeComponent();
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
progressBar1.SetBinding(System.Windows.Controls.ProgressBar.ValueProperty, new Binding("TotalPercentCompleted"));
progressBar1.DataContext = FileDownloadClass;
FileDownloadClass.PropertyChanged +=new PropertyChangedEventHandler(FileDownloadClass_PropertyChanged);
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
FileDownloadClass.DownloadFiles();
if ((bw.CancellationPending == true))
e.Cancel = true;
else
{
bw.ReportProgress(FileDownloadClass.TotalPercentCompleted);
}
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if ((e.Cancelled == true))
{
this.lblConnectionStatus.Content = " Download Canceled!";
}
else if (!(e.Error == null))
{
this.lblConnectionStatus.Content = ("Error: " + e.Error.Message);
}
else
{
this.lblConnectionStatus.Content = "Done!";
}
}
private void FileDownloadClass_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
lblKbCompleted.Content = e.ProgressPercentage.ToString();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
bw.RunWorkerAsync();
}
}
}
Edit: DownloadFile Class Code
sealed class DownloadFile:INotifyPropertyChanged
{
#region Private Fields
// These fields hold the values for the public properties.
private int progressBarValue = 0;
private int totalKbCompleted = 0;
private int totalBytesReceived = 0;
private int remoteFileSize = 0;
private string fileName = String.Empty;
private string statusMessage = String.Empty;
#endregion
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
#region Public Properties
public int TotalKbCompleted
{
get { return this.totalKbCompleted; }
set
{
if (value != this.totalKbCompleted)
{
this.totalKbCompleted = value/1024;
NotifyPropertyChanged("TotalKbCompleted");
}
}
}
public int TotalBytesReceived
{
get { return this.totalBytesReceived; }
set
{
if (value != this.totalBytesReceived)
{
this.totalBytesReceived = value;
NotifyPropertyChanged("TotalBytesReceived");
}
}
}
public int RemoteFileSize
{
get { return this.remoteFileSize; }
set
{
if (value != this.remoteFileSize)
{
this.remoteFileSize = value;
NotifyPropertyChanged("RemoteFileSize");
}
}
}
public string CurrentFileName
{
get { return this.fileName; }
set
{
if (value != this.fileName)
{
this.fileName = value;
NotifyPropertyChanged("CurrentFileName");
}
}
}
public string StatusMessage
{
get { return this.statusMessage; }
set
{
if (value != this.statusMessage)
{
this.statusMessage = value;
NotifyPropertyChanged("StatusMessage");
}
}
}
#endregion
public Int16 DownloadFiles()
{
try
{
statusMessage = "Attempting Connection with Server";
DoEvents();
// create a new ftpclient object with the host and port number to use
FtpClient ftp = new FtpClient("mySite", 21);
// registered an event hook for the transfer complete event so we get an update when the transfer is over
//ftp.TransferComplete += new EventHandler<TransferCompleteEventArgs>(ftp_TransferComplete);
// open a connection to the ftp server with a username and password
statusMessage = "Connected. Authenticating ....";
ftp.Open("User Name", "Password");
// Determine File Size of the compressed file to download
statusMessage = "Getting File Details";
RemoteFileSize = Convert.ToInt32(ftp.GetFileSize("myFile.exe"));
ftp.TransferProgress += new EventHandler<TransferProgressEventArgs>(ftp_TransferProgress);
statusMessage = "Download from Server";
ftp.GetFile("myFile.exe", "E:\\Test\\myFile.exe", FileAction.Create);
// close the ftp connection
ftp.Close();
statusMessage = "Download Complete";
return 1;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
return 0;
}
}
private void ftp_TransferProgress(object sender, TransferProgressEventArgs e)
{
totalBytesReceived = Convert.ToInt32(e.BytesTransferred.ToString());
totalKbCompleted = Convert.ToInt32(totalKbCompleted + Convert.ToInt32(totalBytesReceived));
progressBarValue = totalKbCompleted;
}
}
You can use control binding:
Windows Forms:
progressBar1.DataBindings.Add("Value", dataSource, dataMember, true,
DataSourceUpdateMode.OnPropertyChanged);
where the dataSource is your class. and the dataMember is the property name in that class "TotalProgress".
Edit: For WPF
progressBar1.SetBinding(ProgressBar.ValueProperty, new Binding("ProgressTotal"));
progressBar1.DataContext = the instance of the class you want to bind to its property;
For more information about wpf data binding check this and this.
Edit2: Here is an full example:
Foo _foo = new Foo();
DispatcherTimer _dispatcherTimer = new DispatcherTimer();
public MainWindow()
{
InitializeComponent();
_dispatcherTimer.Interval = TimeSpan.FromSeconds(1);
_dispatcherTimer.Tick += _dispatcherTimer_Tick;
_dispatcherTimer.Start();
progressBar1.SetBinding(ProgressBar.ValueProperty, new Binding("ProgressTotal"));
progressBar1.DataContext = _foo;
}
private void _dispatcherTimer_Tick(object sender, EventArgs e)
{
_foo.ProgressTotal = (_foo.ProgressTotal + 10) % progressBar1.Maximum;
}
public class Foo : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private double _progressTotal = 0;
public double ProgressTotal
{
get { return _progressTotal; }
set
{
if (value != _progressTotal)
{
_progressTotal = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("ProgressTotal"));
}
}
}
}
}
Edit: Add a timer to preview the effect.
Edit: After you uploading your code, the problem appears in two positions:
The name of the variable is TotalKbCompleted no TotalPercentCompleted. so change the binding line to:
progressBar1.SetBinding(System.Windows.Controls.ProgressBar.ValueProperty, new Binding("TotalKbCompleted"));
You are updating the totalKbCompleted instead of TotalKbCompleted so the property changed will not trigger.
I have a class that implements the INotifyPropertyChanged interface.
If I create a new instance of the object, the PropertyChanged event gets set after I retrieve a value from it.
Example:
MyItem itm = new MyItem(); //MyItem.PropertyChanged == null
string test = itm.Value; //MyItem.PropertyChanged != null
If I assign itm the value of another MyItem, the PropertyChanged event remains null.
Example:
itm = (MyItem)cboMyItemsCombobox.SelectedItem; // Properties for itm change to the values
// of the selected item, but PropertyChanged
// == null
I believe the problem lies partially in my custom constructor for the class, but I'm not entirely sure.
The goal is to have a variable to hold data for a record, called mnuitm, that is bound to
3 textbox objects. When the text in a textbox changes, the change is made to the property in mnuitm. When the property in mnuitm is changed, the change is made in the textbox.
This works if I create a new MenuItem and assign the values individually, but does not work if I assign an already populated MenuItem to mnuitm.
Here is my actual code for (hopefully) more clearity on the issue.
public partial class frmMenuItems : Form
{
private class MenuItem : INotifyPropertyChanged
{
private Int32 mid;
private string txt;
private string url;
private string scp;
public MenuItem() { }
public MenuItem(Int32 id, string txt, string url, string scp)
{
ID = id;
Text = txt;
URL = url;
Script = scp;
}
public Int32 ID
{
get
{
return mid;
}
set
{
if (mid != value)
{
mid = value;
NotifyPropertyChanged("ID");
}
}
}
public string Text {
get
{
return txt;
}
set
{
if (txt != value)
{
txt = value;
NotifyPropertyChanged("Text");
}
}
}
public string URL {
get
{
return url;
}
set
{
if (url != value)
{
url = value;
NotifyPropertyChanged("URL");
}
}
}
public string Script {
get
{
return scp;
}
set
{
if (scp != value)
{
scp = value;
NotifyPropertyChanged("Script");
}
}
}
public void Clear()
{
ID = 0;
Text = "";
URL = "";
Script = "";
}
public override string ToString()
{
return Text;
}
private void NotifyPropertyChanged(string inf)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(inf));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
private MenuItem mnuitm;
private MySqlConnection sqlcon;
public frmMenuItems()
{
InitializeComponent();
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnCancel_Click(object sender, EventArgs e)
{
mnuitm.Clear();
}
private void frmMenuItems_Load(object sender, EventArgs e)
{
string constr = "server={0};uid={1};pwd={2};database={3};";
DBItem dbi = CountyDataManager.CountyData.DBConnection;
constr = string.Format(constr, [MyHost], [MyUsername], [MyPassword], [MyDatabase]);
sqlcon = new MySqlConnection(constr);
sqlcon.Open();
mnuitm = new MenuItem();
SetBindings();
RefreshList();
}
private void SetBindings()
{
txtMenuText.DataBindings.Clear();
txtURL.DataBindings.Clear();
txtScript.DataBindings.Clear();
txtMenuText.DataBindings.Add("Text", mnuitm, "Text");
txtURL.DataBindings.Add("Text", mnuitm, "URL");
txtScript.DataBindings.Add("Text", mnuitm, "Script");
}
private void RefreshList()
{
using (MySqlCommand cmd = new MySqlCommand("SELECT `menuid`,`menutext`,`url`,`script` FROM tblindexmenu ORDER BY `menutext`", sqlcon))
{
lstMenuItems.Items.Clear();
using (MySqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
lstMenuItems.Items.Add(new MenuItem(Int32.Parse(rdr[0].ToString()), rdr[1].ToString(),rdr[2].ToString(),rdr[3].ToString()));
}
}
}
}
private void frmMenuItems_FormClosing(object sender, FormClosingEventArgs e)
{
sqlcon.Close();
}
private void lstMenuItems_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstMenuItems.SelectedIndex > -1)
{
mnuitm = (MenuItem)lstMenuItems.SelectedItem;
}
}
}
After receiving feedback, I made the following changes:
Added CopyFrom() to MenuItem
public void CopyFrom(MenuItem itm)
{
this.ID = itm.ID;
this.URL = itm.URL;
this.Text = itm.Text;
this.Script = itm.Script;
}
I then modified the SelectedIndexChanged code to use the new function
mnuitm.CopyFrom((MenuItem)lstMenuItems.SelectedItem);
This is by design. When you write
itm = (MyItem)cboMyItemsCombobox.SelectedItem;
you haven't changed any of the properties of the MenuItem itm used to point to, rather you changed the MenuItem itm points to.
One option for what you need is add a function to MenuItem that looks like
SetFromOtherMenuItem(MenuItem other)
{
this.Url = other.Url
//etc
}
Again, PropertyChanged means that a property on some instance has changed. In your case, only one of the variables pointing to that instance changed (to point to a different instance).
I have a gridview and, when a record is double-clicked, I want it to open up a new detail-view form for that particular record.
As an example, I have created a Customer class:
using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Collections;
namespace SyncTest
{
#region Customer Collection
public class CustomerCollection : BindingListView<Customer>
{
public CustomerCollection() : base()
{
}
public CustomerCollection(List<Customer> customers) : base(customers)
{
}
public CustomerCollection(DataTable dt)
{
foreach (DataRow oRow in dt.Rows)
{
Customer c = new Customer(oRow);
this.Add(c);
}
}
}
#endregion
public class Customer : INotifyPropertyChanged, IEditableObject, IDataErrorInfo
{
private string _CustomerID;
private string _CompanyName;
private string _ContactName;
private string _ContactTitle;
private string _OldCustomerID;
private string _OldCompanyName;
private string _OldContactName;
private string _OldContactTitle;
private bool _Editing;
private string _Error = string.Empty;
private EntityStateEnum _EntityState;
private Hashtable _PropErrors = new Hashtable();
public event PropertyChangedEventHandler PropertyChanged;
private void FirePropertyChangeNotification(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
public Customer()
{
this.EntityState = EntityStateEnum.Unchanged;
}
public Customer(DataRow dr)
{
//Populates the business object item from a data row
this.CustomerID = dr["CustomerID"].ToString();
this.CompanyName = dr["CompanyName"].ToString();
this.ContactName = dr["ContactName"].ToString();
this.ContactTitle = dr["ContactTitle"].ToString();
this.EntityState = EntityStateEnum.Unchanged;
}
public string CustomerID
{
get
{
return _CustomerID;
}
set
{
_CustomerID = value;
FirePropertyChangeNotification("CustomerID");
}
}
public string CompanyName
{
get
{
return _CompanyName;
}
set
{
_CompanyName = value;
FirePropertyChangeNotification("CompanyName");
}
}
public string ContactName
{
get
{
return _ContactName;
}
set
{
_ContactName = value;
FirePropertyChangeNotification("ContactName");
}
}
public string ContactTitle
{
get
{
return _ContactTitle;
}
set
{
_ContactTitle = value;
FirePropertyChangeNotification("ContactTitle");
}
}
public Boolean IsDirty
{
get
{
return ((this.EntityState != EntityStateEnum.Unchanged) || (this.EntityState != EntityStateEnum.Deleted));
}
}
public enum EntityStateEnum
{
Unchanged,
Added,
Deleted,
Modified
}
void IEditableObject.BeginEdit()
{
if (!_Editing)
{
_OldCustomerID = _CustomerID;
_OldCompanyName = _CompanyName;
_OldContactName = _ContactName;
_OldContactTitle = _ContactTitle;
}
this.EntityState = EntityStateEnum.Modified;
_Editing = true;
}
void IEditableObject.CancelEdit()
{
if (_Editing)
{
_CustomerID = _OldCustomerID;
_CompanyName = _OldCompanyName;
_ContactName = _OldContactName;
_ContactTitle = _OldContactTitle;
}
this.EntityState = EntityStateEnum.Unchanged;
_Editing = false;
}
void IEditableObject.EndEdit()
{
_Editing = false;
}
public EntityStateEnum EntityState
{
get
{
return _EntityState;
}
set
{
_EntityState = value;
}
}
string IDataErrorInfo.Error
{
get
{
return _Error;
}
}
string IDataErrorInfo.this[string columnName]
{
get
{
return (string)_PropErrors[columnName];
}
}
private void DataStateChanged(EntityStateEnum dataState, string propertyName)
{
//Raise the event
if (PropertyChanged != null && propertyName != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
//If the state is deleted, mark it as deleted
if (dataState == EntityStateEnum.Deleted)
{
this.EntityState = dataState;
}
if (this.EntityState == EntityStateEnum.Unchanged)
{
this.EntityState = dataState;
}
}
}
}
Here is my the code for the double-click event:
private void customersDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
Customer oCustomer = (Customer)customersBindingSource.CurrencyManager.List[customersBindingSource.CurrencyManager.Position];
CustomerForm oForm = new CustomerForm();
oForm.NewCustomer = oCustomer;
oForm.ShowDialog(this);
oForm.Dispose();
oForm = null;
}
Unfortunately, when this code runs, I receive an InvalidCastException error stating "Unable to cast object to type 'System.Data.DataRowView' to type 'SyncTest.Customer'".
This error occurs on the very first line of that event:
Customer oCustomer = (Customer)customersBindingSource.CurrencyManager.List[customersBindingSource.CurrencyManager.Position];
What am I doing wrong?... and what can I do to fix this? Any help is greatly appreciated.
Thanks!
EDIT:
Here is how the data is populated:
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'northwindDataSet.Customers' table. You can move, or remove it, as needed.
this.customersTableAdapter.Fill(this.northwindDataSet.Customers);
}
It looks like your object is of type System.Data.DataRowView, not Customer. Your code returns Dataset instead of objects that you are expecting. You need to modify the code that returns your objects.
How about using BindingSource.Current instead of CurrentManager? But from the looks of it, your data source is a DataSet.
private void customersDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
DataGridView grid = (DataGridView) sender;
Customer customer = (Customer) grid.Rows[e.RowIndex].DataBoundItem;
}
Checks removed for brevity
Customer oCustomer = (Customer)
((DataRowView)customersBindingSource.Current).Row;
When you get the invalid cast as you have described it is due to the object is not the type you think it should be.
You can avoid the exception by using the as keyword.
Customer oCustomer = (Customer)customersBindingSource.CurrencyManager.List[customersBindingSource.CurrencyManager.Position];
becomes
Customer oCustomer = customersBindingSource.CurrencyManager.List[customersBindingSource.CurrencyManager.Position] as Customer;
If it is an invalid cast then oCustomer will be null.
Now if you are still getting the null then the object from List is not a Customer object. I would use the debugger to determine what the object is and how you would go about casting it to your Cusomter object.
You will never be able to convert directly to the Customer object because your error is
InvalidCastException error stating "Unable to cast object to type 'System.Data.DataRowView' to type 'SyncTest.Customer'". is giving you an DataRowView object. You need take the row and pull the values from the row.