I've set the combobox data in the c# code, I would like to write to the database with a number rather than the text in the combobox; for instance I would like to have:
1 - View Only = 1
2 - Basic User = 2
3 - Supervisor = 3
4 - Administrator = 4
5 - Super User = 5
I've no idea how to do this. Below is what I've got so far.
private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
// ... A List.
List<string> data = new List<string>();
data.Add("1 - View Only");
data.Add("2 - Basic User");
data.Add("3 - Supervisor");
data.Add("4 - Administrator");
data.Add("5 - Super User");
// ... Get the ComboBox reference.
var comboBox = sender as ComboBox;
// ... Assign the ItemsSource to the List.
comboBox.ItemsSource = data;
// ... Make the first item selected.
comboBox.SelectedIndex = 0;
}
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// ... Get the ComboBox.
var comboBox = sender as ComboBox;
// ... Set SelectedItem as Window Title.
string value = comboBox.SelectedItem as string;
this.Title = "Selected: " + value;
}
So to sum up my ideal outcome - When someone selects "1 - View Only" from the combobox it sets the user level in the database to 1.
Thanks
For something simplistic, you can use comboBox.SelectedIndex + 1, but that will break down if the order of your items changes somehow.
For something slightly more elaborate, you could do the following:
namespace ComboBoxExampleWPF
{
class UserLevel
{
public UserLevel(int level, string description)
{
Level = level;
Description = description;
}
public int Level { get; private set; }
public string Description { get; private set; }
// This controls how it shows up in the comboBox
public override string ToString()
{
return Level.ToString() + " - " + Description;
}
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<UserLevel> list = new List<UserLevel>()
{
new UserLevel(1, "View Only"),
new UserLevel(2, "Basic User"),
new UserLevel(3, "Supervisor"),
new UserLevel(4, "Administrator"),
new UserLevel(5, "Super User")
};
comboBox1.ItemsSource = list;
comboBox1.SelectionChanged += comboBox1_SelectionChanged;
}
void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// ... Get the ComboBox.
var comboBox = sender as ComboBox;
// ... Set SelectedItem as Window Title.
UserLevel value = comboBox.SelectedItem as UserLevel;
this.Title = "Selected: " + value.ToString();
SetUserLevel(value);
}
private void SetUserLevel(UserLevel ul)
{
// _myDatabase.SetUserLevel(ul.Level);
}
}
}
Related
I have a simple database with 2 tables (product and category) and the code below is to create a new product in the product table under one of the categories selected in the combo box.
public partial class frmAddProduct : Form
{
public frmAddProduct()
{
InitializeComponent();
db = new DatabaseEntities();
}
DatabaseEntities db;
string category = "";
Product _product;
private void frmAddProduct_Load(object sender, EventArgs e)
{
categoryBindingSource.DataSource = db.Categories.ToList();
CategoryList();
}
private void CategoryList()
{
var list = db.Categories.ToList();
cboCategory.DataSource = list;
cboCategory.DisplayMember = "CategoryName";
cboCategory.ValueMember = "CategoryID";
if (cboCategory.Items.Count > 1)
cboCategory.SelectedIndex = -1;
}
private void btnNew_Click_1(object sender, EventArgs e)
{
_product = new Product();
int id = int.Parse(txtID.Text);
decimal price = decimal.Parse(txtPrice.Text);
int qty = int.Parse(txtPrice.Text);
_product.ProductID = id;
_product.ProductName = txtName.Text;
_product.UnitPrice = price;
_product.UnitsInStock = qty;
_product.CategoryID = int.Parse(category);
db.Products.Add(_product);
db.SaveChanges();
}
private void cboCategory_SelectedIndexChanged(object sender, EventArgs e)
{
category = cboCategory.SelectedValue.ToString();
}
}
When I run the form an error appears saying "Additional information: Object reference not set to an instance of an object". The error refers to the next line in the code:
category = cboCategory.SelectedValue.ToString();
Does anyone know what is the problem here?
One note: CategoryID is an integer field in the database.
It looks like your setting of the SelectedIndex to -1 is triggering SelectedIndexChanged event with nothing in SelectedValue which you are trying to read in the handler. You might be missing check for null in the handler.
I have two comboboxes where the first one has categories (and I can fill that easily from the source file). The trick is having the second combobox show only the items that are associated with the chosen category from the first combobox. For example:
cb1 is populated from a sourcefile with the category values 1, 2, 3 & 4 and cb2 is populated with values A,B,C,D,E,F,G,H
What I am failing at doing is limiting what is seen in cb2. So when cb1's value is "1", I only want "A" and "B" to be visible in cb2, and if cb1 changes to "2" I only want "C" and "D" to be visible.
For winforms :
If you have a form with 2 combo boxes (cb1, cb2) you could use something like this? (obviously modified to support your data objects).
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//create a list for data items
List<MyComboBoxItem> cb1Items = new List<MyComboBoxItem>();
//assign sub items
cb1Items.Add(new MyComboBoxItem("1")
{
SubItems = { new MyComboBoxItem("A"), new MyComboBoxItem("B") }
});
cb1Items.Add(new MyComboBoxItem("2")
{
SubItems = { new MyComboBoxItem("C"), new MyComboBoxItem("D") }
});
cb1Items.Add(new MyComboBoxItem("3")
{
SubItems = { new MyComboBoxItem("E"), new MyComboBoxItem("F") }
});
cb1Items.Add(new MyComboBoxItem("4")
{
SubItems = { new MyComboBoxItem("G"), new MyComboBoxItem("H") }
});
//load data items into combobox 1
cb1.Items.AddRange(cb1Items.ToArray());
}
private void cb1_SelectedIndexChanged(object sender, EventArgs e)
{
//get the combobox item
MyComboBoxItem item = (sender as ComboBox).SelectedItem as MyComboBoxItem;
//make sure no shinanigans are going on
if (item == null)
return;
//clear out combobox 2
cb2.Items.Clear();
//add sub items
cb2.Items.AddRange(item.SubItems.ToArray());
}
}
public class MyComboBoxItem
{
public string Name;
public List<MyComboBoxItem> SubItems = new List<MyComboBoxItem>();
public MyComboBoxItem(string name)
{
this.Name = name;
}
public override string ToString()
{
return Name;
}
}
I am developing a Windows phone App and in my MainPage.xaml.cs file I have one private member that is being changed in the overrided method OnNavigateTo(). Although its value is changed, after that in the MainPage constructor its value resets to 0 (It's an int member). I guess that OnNavigateTo() method is being called BEFORE the constructor but if so I would have a nullReferenceException. What can cause that problem?
The OnNavigateTo() Function:
if (NavigationContext.QueryString.ContainsKey("leftDuration"))
{
//Get the selected value from IntroductionPage as a string
var leftRecievedInformation = NavigationContext.QueryString["leftDuration"];
//Convert the string to an enum object
var firstRunLeftChosenDuration = (LensLifetime)Enum.Parse(typeof(LensLifetime), leftRecievedInformation);
//Set the leftDuration value to the model object
_firstRunLeftDuration = getDurationAsNumber(firstRunLeftChosenDuration);
MessageBox.Show(_firstRunLeftDuration + "");
model.Left.LifeTime = _firstRunLeftDuration;
}
My problematic member is the _firstRunLeftDuration value. Although, as you can see, i set the model.Left.LifeTime value, in the MainPage.xaml I still get the default 0 value... It' like completely ignoring this line of code.. I know the code is not particularly clear but I don't think its beneficial to add extra lines of useless code.
Here's the MainPage.xaml.cs file:
public partial class MainPage : PhoneApplicationPage
{
public ContactLensesModel model;
private int _firstRunLeftDuration, _firstRunRightDuration; //Members used for the initialization of the app
public int FirstRunLeftDuration
{
get
{
return _firstRunLeftDuration;
}
set
{
_firstRunLeftDuration = value;
}
}
public int FirstRunRightDuration
{
get
{
return _firstRunRightDuration;
}
set
{
_firstRunRightDuration = value;
}
}
public ContactLensesModel Model
{
get
{
return model;
}
set
{
model = value;
}
}
// Constructor
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
BuildLocalizedApplicationBar();
//Should check if the user starts the app for the first time....
//Create a new model
Model = new ContactLensesModel();
Model.setLeftNewStartingDate();
Model.setRightNewStartingDate();
//Should load the already saved model if the user in not entering for the first time...
//....
//....
loadModel();
//Connect the data Context
leftLensDaysRemaining.DataContext = Model.Left;
rightLensDaysRemaining.DataContext = Model.Right;
}
private int getDurationAsNumber(LensLifetime duration)
{
if (duration.Equals(LensLifetime.Day))
return 1;
else if (duration.Equals(LensLifetime.Two_Weeks))
return 14;
else
return DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//Get the arguments as strings and convert them to an enum, is true only when the user enters app for the first time.
if (NavigationContext.QueryString.ContainsKey("leftDuration"))
{
//Get the selected value from IntroductionPage as a string
var leftRecievedInformation = NavigationContext.QueryString["leftDuration"];
//Convert the string to an enum object
var firstRunLeftChosenDuration = (LensLifetime)Enum.Parse(typeof(LensLifetime), leftRecievedInformation);
//Set the leftDuration value to the model object
FirstRunLeftDuration = getDurationAsNumber(firstRunLeftChosenDuration);
Model.Left.LifeTime = FirstRunLeftDuration;
}
if (NavigationContext.QueryString.ContainsKey("rightDuration"))
{
//Get the selected value from IntroductionPage as a string
var rightRecievedInformation = NavigationContext.QueryString["rightDuration"];
//Convert the string to an enum object
var firstRunRightChosenDuration = (LensLifetime)Enum.Parse(typeof(LensLifetime), rightRecievedInformation);
//Set the leftDuration value to the model object
_firstRunRightDuration = getDurationAsNumber(firstRunRightChosenDuration);
Model.Right.LifeTime = _firstRunRightDuration;
}
}
/// <summary>
/// Loads the model from the isolated Storage
/// </summary>
private void loadModel()
{
//Load the model...
}
private void BuildLocalizedApplicationBar()
{
// Set the page's ApplicationBar to a new instance of ApplicationBar.
ApplicationBar = new ApplicationBar();
// Create a new button and set the text value to the localized string from AppResources.
ApplicationBarIconButton appBarSettingsButton = new ApplicationBarIconButton(new Uri("/Assets/Icons/settingsIcon4.png", UriKind.Relative));
appBarSettingsButton.Text = AppResources.AppBarSettingsButtonText;
appBarSettingsButton.Click += appBarButton_Click;
ApplicationBar.Buttons.Add(appBarSettingsButton);
// Create a new menu item with the localized string from AppResources.
//ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
//ApplicationBar.MenuItems.Add(appBarMenuItem);
}
void appBarButton_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/SettingsPage.xaml", UriKind.RelativeOrAbsolute));
}
private void leftButtonChange_Click(object sender, RoutedEventArgs e)
{
model.setLeftNewStartingDate();
}
private void rightChangeButton_Click(object sender, RoutedEventArgs e)
{
model.setRightNewStartingDate();
}
}
}
The OnNavigatedTo method cannot be called before the constructor. The constructor is always executed first. I think your model.Left.LifeTime doesn't raise a PropertyChanged event. Hence, your View won't know you are giving it a value. Therefore it will show the default value of model.Left.Lifetime which is probably 0.
On the other hand, it's hard to tell without seeing the rest of your code.
I've set up a simple form. A ListBox takes values from a list in the 'business object' displaying the Name property and providing the Value property.
In additon the ListBox's SelectedItem property is bound to a property in the same business object.
Using the UI to select a value from the list correctly changes the objects property (checked when the button is clicked) and the correct value is available. So far so good.
However, if the ListBox's SelectedIndex property is changed in the code, then the UI correctly changes as expected but the business property does not change - it would appear to have missed the change event. This is true for both setting in the constructor and in the button event handler (see the code).
What have I missed or what am I doing incorrectly.
(I've only included the code I've written - not VS wizard generated stuff)
class Frequency
{
public String Name { get; set; }
public Int16 Value { get; set; }
public Frequency(String name, Int16 value)
{
Name = name;
Value = value;
}
}
class FrequencyList : System.ComponentModel.BindingList<Frequency>
{
}
class Model
{
public static FrequencyList FrequencyValues = new FrequencyList()
{
new Frequency("Slowest", 100),
new Frequency("Slow", 150),
new Frequency("Medium", 1000),
new Frequency("Fast", 5500),
new Frequency("Fastest", 10000)
};
public Frequency StartFrequency { get; set; }
public void DoStuff()
{
if (StartFrequency == null)
return;
Int16 freq = StartFrequency.Value;
}
}
public partial class Form1 : Form
{
private Model myModel = new Model();
public Form1()
{
InitializeComponent();
// Bind the list to a copy of the static model data
this.listBox1.DataSource = Model.FrequencyValues;
// Bind the control to the model value
this.listBox1.DataBindings.Add("SelectedItem", myModel, "StartFrequency");
// Select the start value
this.listBox1.SelectedIndex = 3;
}
private void button1_Click(object sender, EventArgs e)
{
Int16 f = (Int16)listBox1.SelectedValue;
this.myModel.DoStuff();
int new_index = listBox1.SelectedIndex + 1;
if (new_index >= listBox1.Items.Count)
new_index = 0;
listBox1.SelectedIndex = new_index;
}
}
You don't want the Click event, you want the SelectedIndexChanged event. This will trigger regardless of whether the user or the program instigates the change.
How to setup a multi value dropdownlist from a list collection...
Datasource: Listcollection which contains ColorCode and Description...
how to I setup a dropdown with Colorcode-Description like ORG-orange...
then how to capture these selected value as colorcode only by removing description for update purpose...
Now I am doing like this...
ddl.datesource=list<datasetvalues> // ...contains (colorcode, description)
ddl.DataTextField = "ColorCode";
ddl.DataValueField = "ColorCode";
ddl.databind();
then selected value should be like this...
ddlcolor.Items.FindByValue((DataBinder.Eval(formView1.DataItem,
"colorCode").ToString())).Selected = true;
for update:
ClassA.Color= ddl.selectedvalue();
Now what I need change to in the above code to get the combination of both..otherwise i need have textbox for description which syncs with ddl..which is bit complex for my level of programming...thanks..
There are a couple of solutions as per my knowlege.
1) You can concatenate the text like : Code + "-" + Value, while preparing the list using a For/Foreach... loop
2) If it is permitted as per your project, you may also consider overriding the string inside the entity but the selected value will be with a hyphenated(with a - inbetween code & value) string, which you need to string split in the code behind.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<CodeValue> colors = new List<CodeValue> {new CodeValue{Code="",Value="Select"},new CodeValue{Code="RD",Value="Red"},
new CodeValue{Code="BL",Value="Blue"}};
ddlColors.DataSource = colors;
ddlColors.DataBind();
}
}
protected void btnClick_Click(object sender, EventArgs e)
{
var item = ddlColors.SelectedValue;
var code = item.Split('-');
}
}
class CodeValue
{
public string Code { get; set; }
public string Value { get; set; }
public override string ToString()
{
return this.Code + "-" + this.Value;
}
}