How to refer to an object name through a variable? - c#

I have some code that will open a sqllite database, get some street names, and populate a list box that is then attached to a combo-box so it can suggest the names as the user types them. I want to make a procedure that I can call to do this since it will be used on may different combo-boxes. I can pass it the name of the control, but how do I modify attributes of a contol while referring to it as a variable?
Something like:
string A = "cbSTreets"
[A].text = "Sets the Text for the combo box."
If someone could just point me in the right direction I would appreciate it.

Instead of passing it as the name of a control, why not just pass the control itself (especially if they're all comboboxes and the same type?)
Alternatively if for some reason you can't pass the control itself, you could set something up with a datastructure like a dictionary if you need to use the string name:
Dictionary<string, ComboBox> comboBoxes = new Dictionary<string, ComboBox>();
//Use the string you want to refer to the combobox and the combobox item itself
comboBoxes.Add("bcbsTreets", comboBox1);
//Use the name as defined in the previous step to get the reference to the combobox and
//set the text
comboBoxes["bcbsTreets"].Text = "whatever";

You could try something like this:
private void SetText(List<string> streets, ComboBox cb)
{
cb.DataSource = streets;
}
Of course, you'll need to fill the streets from your database and pass in the ComboBox control you want to populate. You can use another collection if you like, but ComboBox datasources need to implement the IList interface.

This is only possible via reflection and should be avoided!
You should do this the normal way.
For the solution how to do it with reflection, look here: How to access class member by string in C#?

Related

WPF Datagrid UserControl with definable columns

I have an object something like this:
public class Item
{
public string Name;
public int Id;
public int Quantity;
public decimal Volume;
public decimal Cost;
}
I'm wanting to create a reusable user control which would take a list of these objects and display them in a datagrid. The trick is that I want to specify which of the properties are shown in the datagrid for each instance of the control. Unfortunately my WPF skills are not up to the tasks and I don't want to create a specific control for each combination that I will want to use, as that feels like a lot of work for very similar code items. Any help to pointers of how to accomplish this would be greatly appreciated.
You can use the Columns property of your datagrid to interact with the columns and hide the columns you don't want.
datagrid.Columns.RemoveAt(IndexOftheColumn);
or if you named your columns
datagrid.Columns.RemoveAll(x => x.Name = "column name");
or if it is possible that you will need to column later
datagrid.Columns[IndexOftheColumn].Visibility = Visibility.Collapsed;
It is also possible to do this with pure Xaml with bindings but since you are new to Wpf I would suggest doing it in the code behind (the .cs of your Wpf control) first.
As for selecting which columns to hide you can pass a list of names for the columns you want to remove in the constructor of the control or with a binding. There are a lot of ways to do it.
Or you could do the opposite and add columns dynamically based on your needs.
Note that this question has been asked before

How to display selective items in a binding list in grid control

I have implemented below code:
gridControl.DataSource = CusColumnList
CusColumnList is of type MyBindingList which inherits BindingList, in my case T is class MyColumn. The binding works well.
But now my problem comes, I don't want the data source to bind to every column in CusColumnList, I only want it binds to column whose name contains "ABC" or whose display name contains "XYZ". I tried to set
gridControl.DataSource = CusColumnList.Where(column => column.Name.Contains("ABC") || column.DisplayName.Contains("XYZ"));
But seems it does not work.
I also tried to create another bindinglist collection MyTempCusColumnList of type MyBindingList, and in the Get method of this MyTempCusColumnList, I just return every item in CusColumnList where the name or display name qualifies. But in this way, every time when CusColumnList is updated, I need to manually update MyTempCusColumnList.
I wonder whether there is a better way to archive this goal with just CusColumnList.
Thanks!
Edit : format code
You could use a filter string on a BindingSource object.
Check out the MSDN documentation on it, it's quite good: http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.filter(v=vs.100).aspx

Reference control using string with value of name

Is there a way in C# to reference a control, in my case a TextBox, by using the value of a string variable? I am using the code below to make a single method that multiple control can use for the 'LostFocus' event. The sender TextBox then needs to calculate results based on the contents of other TextBoxes. The problem is that there are about 12 rows of TextBoxes, and while this code works to reuse the event method, I can't think of a way to reference the correct boxes that are not the sender. All of the boxes have similar names (ex - miCellSaturation, miCellRecords, orSaturation, orRecords), so my thinking was that if I can isolate part of the TextBox name with a Substring command, and then concatenate that with another string to form the complete TextBox name, this would work. I can do all that, but I don't know of a way to use the concatenated string to reference that box. Would this require iterating through all the boxes until it matches the correct name?
TextBox box = (TextBox)sender;
string boxName = box.Name;
if(boxName.EndsWith("Saturation"))
{
}
Not sure to understand you problem correctly, but if you need to find the references to a particular type of control with its name ending with a predefined string, then you could use
var list = YourForm.Controls.OfType<TextBox>()
.Where(x => x.Name.EndsWith("YourString"));
foreach(TextBox t in list)
{
Console.WriteLine(t.Name);
......
}
This could work only if your searched controls are directly included in the controls collection of the form. If these textboxes are included in some control container then you need to apply these lines to the appropriate control container instead of the form

C# Strange ComboBox Data -- Visual Studio Issue?

I have databinding for my comboboxes set up like this: Show Enum Description Instead of Name
When I am trying to pull the data however, I can't just get the state code, such as IA. I get this long string like: { Value = IA, Description = Iowa }
When I pause the code and look at the combo box values, I am able to do stuff like State.SelectionBoxItem.Value That is an option that expands from the popup menu when you hover over the variable. I can't seem to ever just grab that value programatically though.
Is it a "feature" of visual studio to allow me to break that list down like that?
Is that a string that I will have to break down programatically?
My guess would be you are looking at SelectedItem property not SelectedValue. The string { Value = IA, Description = Iowa } is result of invocation of ToString method of an anonymous type, so yes it is a feature.
In code form another question SelectedValuePath property is not set to Value, which is required to get state code of ListBox selected item through SelectedValue property.

Different Value Member, same control

Edit 1
I believe my problem stems from the following. The function that fills the dropdown portion sets the Display Member to the CountyName. Then when I try and set the SelectedText or EditValue, as has been suggested, that function only returns the CountyID which it try's to match to something in the DropDown list DisplayMember. I need it to match it to something in the ValueMember list.
Using the following I got it to work but it is a HACK and I'd greatly appreciate finding a real solution.
lkuResidenceCounty.ItemIndex = Convert.ToInt32(row["ResidencyCountyID"].ToString());
Original Post
I have a lookup box(DevExpress) on a member form that I fill the possible values in from the DB with this code -->
lkuResidenceCounty.Properties.DataSource = ConnectBLL.BLL.Person.CountyList();
lkuResidenceCounty.Properties.PopulateColumns();
lkuResidenceCounty.Properties.DisplayMember = "CountyName";
lkuResidenceCounty.Properties.ValueMember = "CountyID";
lkuResidenceCounty.Properties.Columns[0].Visible = false;
lkuResidenceCounty.Properties.Columns[2].Visible = false;
lkuResidenceCounty.Properties.Columns[3].Visible = false;
This works just fine as the CountyName is displayed as expected.
However, When I try and load an existing member's value for this field using the below, which is part of a function that takes a row from the DataSet -->
lkuResidenceCounty.Properties.ValueMember = row["ResidencyCountyID"].ToString();
I get a blank box. I have stepped through the code and the correct ID is being returned for the member.
Unfortunately the stored procedure to fill the dropdown options pulls from a Maintenance Table with the columns "CountyName" & "CountyID". So that is correct. Unfortunately, the stored procedure to load a specific person's current county pulls from the Person Table where there is a column called "ResidencyCountyID". It is so named because there is also a "ResponsibilityCountyID" column.
I need a way for them both to coexist, any solutions?
Thanks!
DisplayMember and ValueMember are used to populate the control with the list of selectable values. To set the selected value of a populated LookUpEdit control, set its EditValue property:
lkuResidenceCounty.EditValue = row["ResidencyCountyID"].ToString();
In response to your edit: According to the documentation:
The currently selected row determines values for the editor's edit value and display text. The value for BaseEdit.EditValue is obtained from the RepositoryItemLookUpEditBase.ValueMember field, while the text to display in the edit box is obtained from the RepositoryItemLookUpEditBase.DisplayMember field of the selected row.
When you change BaseEdit.EditValue,
the editor locates and selects the row
whose
RepositoryItemLookUpEditBase.ValueMember
field contains the new value. The text
in the edit box is changed to reflect
the newly selected row.
I don't use these controls but it sounds to me that it shouldn't be working as you described. I think the ToString() is the problem because EditValue accepts an object so it's probably expecting an int for the value. Try:
lkuResidenceCounty.EditValue = (int)row["ResidencyCountyID"];
The ValueMember property tells the list what field to pull from when setting the Value property. Once you've set the ValueMember to "CountyID", then when the list is Databound, it will set all the list items' value properties to their respect objects' CountyID fields.
Hence, you should not do:
lkuResidenceCounty.Properties.ValueMember = row["ResidencyCountyID"].ToString();
but rather
lkuResidenceCounty.Properties.ValueMember = "CountyID";
was perfectly fine, as long as you've correctly identified the field you're trying to databind. Once the list get's databound you should see the results you're expecting.
However, after looking at your code, it seems that you're mismatching your field. In one place you're using ResidencyCountyID and in another you're using CountyID. That is most likely your source of confusion. Figure out what the actual field name is and make sure you set the ValueMember to that.
UPDATE
After reading your comment, what your looking for is the SelectedValue property. The SelectedValue property tells the list to force the selected value to whatever input you give it.
Essentially you have two things going on here. ValueMember tells the list what to use as the value from your data source, and SelectedValue which tells the list what the currently selected value should be.
Why is it that you need the same LookUpEdit to have two value members? Is it being used standalone or in a grid? If standalone, you could swap out the two repository editors depending on the current row. But, are there more than 2 possible values for the ValueMember? That would also complicate things.
UPDATE
Looking at your edit, I think I understand what's going on a little more. So, you don't wish to change your ValueMember (which refers to a data column), but rather to change the value of the editor? If so, then you should definitely use EditValue (not SelectedText, which I don't believe is meant to be set), and assign it to row["value_field"] like so:
lkuResidenceCounty.EditValue = row["ResidencyCountyID"];
What happens when you do that?

Categories

Resources