我有一个带有一些选项的下拉列表。当用户在下拉列表中更改其中一个选项时,我想创建一个注释。问题是我想要说明所做的改变。例如,当货币下拉列表发生变化时,此代码会创建一个注释。因此,如果当前值为“Euro”并且用户将其更改为“Sterling”,我希望该笔记说“货币从欧元变为英镑”等。我知道通过使用selectedItem我可以获得选择的新值,但是如何我在更改之前得到了下拉列表中的值?
if (cust.Currency.ToString() != ddlCustomerCurrency.SelectedItem.Text)
{
Customer.Notes.InsertNote(cust.ID, Company.Current.CompanyID, DateTime.Now, "Currency changed from '" + /*Previous value */ + "' to '" + ddlCustomerCurrency.SelectedItem.Text + "'", CurrentUser.UserID, 1);
}
答案 0 :(得分:2)
您可以将下拉列表的初始值和后续值存储在内存中。然后,每次调用OnChange事件时,只需查看"当前" value并将其与发送到OnChange处理程序的值进行比较。
编辑:这样的事情可能会起到作用:
public class MyClass
{
private string _currentSelectedCurrency;
public void DdlCustomerCurrency_OnChange(object sender, EventArgs e)
{
if (cust.Currency.ToString() != ddlCustomerCurrency.SelectedItem.Text)
{
Customer.Notes.InsertNote(cust.ID, Company.Current.CompanyID, DateTime.Now, "Currency changed from '" + _currentSelectedCurrency +"' to '" + ddlCustomerCurrency.SelectedItem.Text + "'", CurrentUser.UserID, 1);
_currentSelectedCurrency = ((DropDownList) sender).Text
}
}
}
答案 1 :(得分:0)
您可以将当前值保存到ddlDropDown的标记属性,因此您始终将最后选择的值设置为“之前的值”。
样品:
void Main()
{
var currencies = new List<Currency>() {
new Currency { Code="EUR", Name="Euro"},
new Currency { Code="USD", Name="US Dollars"},
new Currency { Code="AUD", Name="Australian Dollars"},
new Currency { Code="JPY", Name="Japanese Yen"},
};
var customer = new Customer { Id=1, Currency="", Notes=new List<string>()};
Form f = new Form {Text="Sample"};
ComboBox ddlCustomerCurrency = new ComboBox { Top=10, Left=10, Tag="",
DataSource=currencies, DisplayMember="Name"};
Button b = new Button {Text = "Show Customer Notes", Top=60, Left = 10};
f.Controls.Add(ddlCustomerCurrency);
f.Controls.Add(b);
ddlCustomerCurrency.SelectedIndexChanged += (sender, args) => {
var cmb = sender as ComboBox;
if (cmb != null)
{
var currency = cmb.SelectedItem as Currency;
var oldValue= cmb.Tag;
if ( currency != null && oldValue != currency.Name )
{
customer.Notes.Add( string.Format(
"\nOld Currency:{0}, New Currency:{1}, Ticks:{2}",
oldValue, currency.Name, DateTime.Now.Ticks) );
cmb.Tag = currency.Name;
}
}
};
b.Click += (sender,args) => {
if (customer.Notes.Any ())
MessageBox.Show( customer.Notes.Last () );
};
f.Show();
}
class Currency
{
public string Code { get; set; }
public string Name { get; set; }
}
class Customer
{
public int Id { get; set; }
public string Currency { get; set; }
public List<string> Notes { get; set; }
}