display the selected dropdown - c#

I am retrieving the credit card type from Database and have to show what credit card type the merchant have used, in the dropdowm. The dropdown has 4 types like Master, Visa, American Express and Discover along with select.
I retrieve it well, but I am not sure how to bind it such that it has all the 4 types along with select but should show the creditcard that has been used.
if (cardtype == 1)
{
ddCreditCardType.SelectedValue = ((int)CommonHelper.CCType.Master).ToString();
}
((int)CommonHelper.CCType.Master).ToString();
//This part gets the type of card used but does not put in the ddCreditCardType.
Please help me out! Thank you!

it looks like your CCType is an enum.
here's what you want to do:
ddCreditCardType.SelectedValue = ((CommonHelper.CCType) cardtype ).ToString();
cardtype is an int, you cast it to your enum type CCType. then convert it to string which returns "Mastercard" or whatever instead of "1" as before. your dropdown probably had the name as its datatext and datavalue bc it didnt have it defined. you would want to set selected value to "1" if your dropdown.DataText = "CardTypeID" or something like that.

The ddCreditCardType.SelectedIndex allows you to set the index.
string TypeOfCard = "Mastercard"; // Replace with your retrieval code
ddCreditCardType.SelectedIndex = ddCreditCardType.Items.IndexOf("Mastercard");
Note that you really must provide error checking because you could get nulls...

Assuming you've just got constants for all the CC types, I'd probably just do something like:
var selectedCardId = ??;
//Make an array of all the card types (this can be a constant)
var cardTypes = new CommonHelper.CCType[]{CommonHelper.CCType.Master, CommonHelper.CCType.Visa, CommonHelper.CCType.Express, CommonHelper.CCType.Whatever};
//Loop through, and build the drop-down
foreach(var card in cardTypes)
{
ddCreditCardType.Items.Add(new ListItem
{
Value = ((int)card).ToString(),
Text = card.ToString(),
IsSelected = (selectedCardId == (int)card)
});
}
I'm sorry, it's been a while since I've done webforms (Or Winforms?)
You'll have to double-check the properties of the list-item thing's.
Good Luck,
Dave

When you build the dropdown, what is the Value in the dropdown. You can choose a text to display and the value behind each item. If your value is CommonHelper.CCType.Master), it should work.

Related

How to remove an item from dropdownlist control in c#

I have a dropwdown list with few items like this(in the format "name-number"):
George Michael - 456456
Justin Dukes - 5644654
Peter Heins - 5456454
Mark Twain - 4454564
Now i have to delete an item from the above list based on the value i have from other query.
My other query gives me a number in string format and i have to remove exactly the same item which is in the above dropdownlist second part(after hyphen).
For ex: My query gives me "5456454".
Now I have to remove the third item(Peter Heins - 5456454) from the dropdownlist which matches with the number my query returns.
I am trying to use
ddl.Items.Remove
But Im not getting what parameter i should pass. Both the text and value fields are same in the dropdownlist and i cannot modify that. So i cannot use
ddl.Items.FindByValue()
Any help?
Thanks in advance.
You could do something like this:
var removeItem = ddl.Items.Cast<ListItem>()
.Where(x => x.Value.Contains(number))
.FirstOrDefault()
ddl.Items.Remove(removeItem);
If you're populating your DropDownList with ListItem objects, I would set the text for example to "Peter Heins - 5456454" and the value to "5456454".
ListItem exampleItem = new ListItem("Peter Heins - 5456454", "5456454");
Then, you could do as you described and call
string value = "5456454";
ListItem valueToRemove = ddl.Items.FindByValue(valueToRemove);
dd1.Remove(valuetoRemove);
edit: If you absolutely cannot change the value (whether it be for school purposes or some other reason) I would do something like this.
string id = "5456454";
foreach (ListItem item in dd1.Items)
{
if (item.Text.Contains(id))
{
dd1.Items.Remove(item);
}
}

Binding BindingList<string[]> to datagridview

Situation:
I am attempting to bind a BindingList<string[]> constructed from a LINQ to SQL query to a DataGridView.
Problem:
I either cannot make modification to the DataGridView after items are generated -or- I get a bunch of unwanted fields in my DataGridView (it depends on which iteration of my code I use) I have googled as hard as I can and tried implementing most of the solutions I have found online to no avail.
I know that string has no public property for its actual value. I am having a difficult time determining how to retrieve that (I believe is part of the problem).
C#
int item = (from p in CurrentConversion.Companies[lbCompanies.SelectedIndex].Modules
where p.ModuleName.Equals(clbModules.SelectedItem)
select p.ModuleId)
.FirstOrDefault();
BindingList<string[]> Data = new BindingList<string[]>((
from p in CurrentConversion.Companies[lbCompanies.SelectedIndex].QuestionAnswers
where p[2].Equals(item)
select new string[] { p[0].ToString(), p[3].ToString() })
.ToList());
dgvQuestions.DataSource = Data;
dgvQuestions.Refresh();
Unwanted Behavior:
This occurs after binding
Question:
Why is this happening?
How do I fix it?
Additional Information:
I am not sure what additional information may be need but I will supply what is requested.
Also if I switch to my other code iteration:
int item = (from p in CurrentConversion.Companies[lbCompanies.SelectedIndex].Modules where p.ModuleName.Equals(clbModules.SelectedItem) select p.ModuleId).FirstOrDefault();
var Data = new BindingList<object>((from p in CurrentConversion.Companies[lbCompanies.SelectedIndex].QuestionAnswers where p[2].Equals(item) select new {Question = p[0].ToString(), Answer = p[3].ToString() }).Cast<object>().ToList());
dgvQuestions.DataSource = Data;
dgvQuestions.Refresh();
dgvQuestions.Columns[1].ReadOnly = false;
I can see the data properly but I cannot edit the column I would like to.
You are binding to a list of string arrays, and you are getting the properties form the array. Most likely you want something like the following:
var Data = new BindingList<object>((
from p in CurrentConversion.Companies[lbCompanies.SelectedIndex].QuestionAnswers
where p[2].Equals(item)
select new {
Val1 = p[0].ToString(),
Val2 = p[3].ToString()
}).ToList());
The reason you're seeing those fields in the Grid is that you're binding each row to a string[]. So it is automatically displaying the properties of string[] as the columns. There is no built-in logic for the grid to parse an array and use the contents of the array as columns.
In order to get the DataGrid to display your data correctly, you should bind it to a custom type, and it will use the public properties of the type as columns.

Enum - combobox binding with one item as exception

I have a Enum which I am binding to ComboBox.
But i dont want to show one enum value in combobox items.
If I try to remove after binding it is throwing error.
cmbDisplayUnit.Items.Remove(item);
Is it possible to binding to enum and still removing or atleast hiding one of the values of Enum?
If you look at this MSDN Forum article it gives an example on how to do what you are wanting. See Sorrocco's answer.
Modified from above link:
string[] TestNames = Enum.GetNames(typeof(SampleEnumUnits));
var list = from test in TestNames where test != "Enum you wish to remove" select Enum.Parse(typeof(SampleEnumUnits), test);
cmbDisplayUnit.ItemsSource = list;
I think you need this:
cmbDisplayUnit.Items.Remove((int)item); // I assume item is enum variable
var items = Enum.GetValues(typeof(datMHD.Enums.EquipmentEnums.Request_ItemType));
var List = items.OfType<datMHD.Enums.EquipmentEnums.Request_ItemType>().ToList();
List.RemoveAll(e => e.Equals(datMHD.Enums.EquipmentEnums.Request_ItemType.Spare_Parts));
You convert the Array values to List then use RemoveAll then Assign the Item to a combo box

Remove a property/column from a generic list

Due to some reason I cannot change the query so I have to do this in C#.
I have a class:
public class myClass
{
int id { get; set; }
string name { get; set; }
DateTime sDate { get; set; }
bool status { get; set; }
}
The data I am getting is fetched in this list. Now what I want is to remove those properties from a list that has null values. I may sound insane but you read it right. I thought of creating another list with only the selected properties, but any of the above properties can be null. So I have to devise a mechanism to filter my list based on this.
For more clarity consider the following example.
List<myClass> lstClass = some data source.
After getting the data the generic list(lstClass) looks like this.Consider the result set in a table:
Id Name Sdate status
1 a null null
2 b null null
3 c null false
Can i some how make my list look like this after removing the property sdate.
So the new list that I want to create should have only three properties.
Id Name status
1 a null
2 b null
3 c false
Any ideas? Can I do this using Linq?
PS: This has nothing to do with presentation. I don’t have a grid where I am not able to hide columns that Is not what I am looking for.
Assuming you have a generic list of myClass instances, you can create an anonymous type with only the needed properties:
List<myClass> list = ...;
var reducedList = list.Select(e => new {e.id, e.name, e.status}).ToList();
// note: call to ToList() is optional
foreach (var item in reducedList)
{
Console.WriteLine(item.id + " " + item.name + " " + item.status);
//note: item does not have a property "sDate"
}
I'm not sure you should solve your issue in the Data, but rather it's a presentation problem.
In which control do you want to display it ? Let's say you display it in DataGrid with AutoGenerateColumns=True, then you can 1) loop on columns/properties 2) for each column/property see if all property values for all rows are null and if so set column's visibility to Collapsed.
If you generate your columns by yourself it's even simpler : only add columns when content is not null for all rows.
If your DB content is dynamic, you might want to bind each row's visibility to a property that would state wether all rows are null or not for that property. Depending on how generic you want your code to be, the code might be very different, and in case you want to have generic solution, using Reflection to retrieve/get/set properties might be of some use.

How to set selected value from Combobox?

I use combobox in c# windows form. I bound the item list as below:
var employmentStatus = new BindingList<KeyValuePair<string, string>>();
employmentStatus.Add(new KeyValuePair<string, string>("0", "[Select Status]"));
employmentStatus.Add(new KeyValuePair<string, string>("1", "Contract"));
employmentStatus.Add(new KeyValuePair<string, string>("2", "Part Time"));
employmentStatus.Add(new KeyValuePair<string, string>("3", "Permanent"));
employmentStatus.Add(new KeyValuePair<string, string>("4", "Probation"));
employmentStatus.Add(new KeyValuePair<string, string>("5", "Other"));
cmbEmployeeStatus.DataSource = employmentStatus;
cmbEmployeeStatus.ValueMember = "Key";
cmbEmployeeStatus.DisplayMember = "Value";
cmbEmployeeStatus.SelectedIndex = 0;
I save the selected value in database eg.1 or 2. Now I want to set selected value from database item like:
cmbEmployeeStatus.SelectedValue =employee.employmentstatus;
But combobox not selected with value. How can I do that?
Try this one.
cmbEmployeeStatus.SelectedIndex = cmbEmployeeStatus.FindString(employee.employmentstatus);
In order to do the database style ComboBoxes manually trying to setup a relationship between a number (internal) and some text (visible), I've found you have to:
Store you items in a list (You are close - except the string,string - need int,string)
DataSource property to the list (You are good)
DataMember,DataValue (You are good)
Load default value (You are good)
Put in value from database (Your question)
Get value to put back in database (Your next question)
First things first. Change your KeyValuePair to so it looks like:
(0,"Select")
(1,"Option 1")
Now, when you run your sql "Select empstatus from employees where blah" and get back an integer, you need to set the combobox without wasting a bunch of time.
Simply: *** SelectedVALUE - not Item ****
cmbEmployeeStatus.SelectedValue = 3; //or
cmbEmployeeStatus.SelectedValue = intResultFromQuery;
This will work whether you have manually loaded the combobox with code values, as you did, or if you load the comboBox from a query.
If your foreign keys are integers, (which for what I do, they all are), life is easy. After the user makes the change to the comboBox, the value you will store in the database is SelectedValue. (Cast to int as needed.)
Here is my code to set the ComboBox to the value from the database:
if (t is DBInt) //Typical for ComboBox stuff
{
cb.SelectedValue = ((DBInt)t).value;
}
And to retrieve:
((DBInt)t).value = (int) cb.SelectedValue;
DBInt is a wrapper for an Integer, but this is part of my ORM that gives me manual control over databinding, and reduces code errors.
Why did I answer this so late? I was struggling with this also, as there seems to be no good info on the web about how to do this. I figured it out, and thought I'd be nice and post it for someone else to see.
In windows Appliation
we use like this
DDLChangeImpact.SelectedIndex = DDLChangeImpact.FindStringExact(ds.Tables[0].Rows[0]["tmchgimp"].ToString());
DDLRequestType.SelectedIndex = DDLRequestType.FindStringExact(ds.Tables[0].Rows[0]["rmtype"].ToString());
Use the SelectedIndex property for the respective employee status in the combo box.
Below will work in your case.
cmbEmployeeStatus.SelectedItem =employee.employmentstatus;
When you set the SelectedItem property to an object, the ComboBox attempts to make that object the currently selected one in the list. If the object is found in the list, it is displayed in the edit portion of the ComboBox and the SelectedIndex property is set to the corresponding index. If the object does not exist in the list, the SelectedIndex property is left at its current value.
EDIT
I think setting the Selected Item as below is incorrect in your case.
cmbEmployeeStatus.SelectedItem =**employee.employmentstatus**;
Like below
var toBeSet = new KeyValuePair<string, string>("1", "Contract");
cmbEmployeeStatus.SelectedItem = toBeSet;
You should assign the correct name value pair.
cmbEmployeeStatus.Text = "text"
I suspect something is not right when you are saving to the db. Do i understand your steps as:
populate and bind
user selects and item, hit and save.. then you save in the db
now if you select another item it won't select?
got more code, especially when saving? where in your code are initializing and populating the bindinglist
A possible solution:
cmbEmployeeStatus.SelectedValue = cmbEmployeeStatus.Items.FindByText("text").Value;
try this
combobox.SelectedIndex = BindingSource.Item(9) where "9 = colum name 9 from table"
To set value in the ComboBox
cmbEmployeeStatus.Text="Something";
Try this:
KeyValuePair<string, string> pair = (KeyValuePair<string,string>)this.ComboBox.SelectedItem;

Categories