LINQ - Accessing a column with the column name as a string parameter - c#

(Similar to this question)
I have tables called 'Questions' and 'FinalFigures':
Questions (QuestionID, Text, FinalFiguresColumnName)
FinalFigures (FinalFigureID, TotalDays, TotalCost, etc, etc)
'FinalFiguresColumnName' would have values like "TotalDays", "TotalCost", etc. Is there a simple way to loop through a set of Questions and have the 'Text' value saved to the corresponding column name on the 'FinalFigures' table?
Ie. instead of:
var item = new FinalFigure();
item.TotalDays = "x";
I need:
var item = new FinalFigure();
// access the column 'TotalDays' with its name as a string, not a property

You can use a bit of reflection to get the property value by the string name of the property instead of directly accessing it.
var value = (int)item.GetType().GetProperty("TotalDays").GetValue(item);
To set the value, simply call SetValue();
item.GetType().GetProperty("TotalDays").SetValue(item, value);

Related

How to insert 'Person or Group' field in list using VS2013?

I am using
string field = list.Fields.Add(StaticName, SPFieldType.User, true);
SPFieldUser user = new SPFieldUser(list.Fields, field);
user.AllowMultipleValues = allowMultiple;
user.Required = Required;
user.SelectionMode = mode;
user.LookupField = "Name";
user.Update();
code sample to create SPUser type of field.
It creates field perfectly fine but in default display value it gives employees' "Account" value instead of "Name" or "Name(with presence). How can I change this display value to "Name" pragmatically.
Thank you.
You can achieve this using two ways:
Just after the creation get the field again and use it (overcast) as SPFieldLookup field because SPUserField is child of SPFieldLookup:
SPFieldLookup userfield = (SPFieldLookup)list.Fields["fieldname"];
Userfield.LookupField = "ImnName";
Userfield.Update();
or you can create the field using AddFieldAsXml method like this:
list.Fields.AddFieldAsXml(#"<Field Name='TypeUser' ID='{99bd898d-c181-4ca9-8397-c9fc032fcdf9}' DisplayName='TypeUser' Type='User' ShowField='ImnName' ></Field>");
list.Update();
you should also take a look at Presence property and set it to true.

Class is showing up in Listbox and not the actual string value

Well firstly this is what is what is happening.
When I select a table from my database from the combo box I want all the column names to appear which they do (Column names are the 'P101','P102' etc ..) but I also want the Extended Property value of each column to appear which for some reason is not displaying.
This is my SP in C#:
[Function(Name = "SP_GET_EXTENDED_PROPERTY", IsComposable = false)]
public ISingleResult<StandardDefinition> GetExtendedProperty(
[Parameter(Name = "#ptableName", DbType = "VARCHAR(50)")] string tableName,
[Parameter(Name = "#pcolumnName", DbType = "VARCHAR(50)")] string columnName)
{
IExecuteResult objResult = this.ExecuteMethodCall(this, (MethodInfo)(MethodInfo.GetCurrentMethod()),tableName, columnName);
ISingleResult<StandardDefinition> objresults = (ISingleResult<StandardDefinition>)objResult.ReturnValue;
return objresults;
}
That Stored Procedure links to this Query in SQL (This query has been tested and works):
SELECT value as _value FROM fn_listextendedproperty
(NULL, 'schema', 'dbo', 'table', 'Acceptance', 'column', 'P101');
The Column name and Tablename i am passing are correct and working after i debug, and the Query in SQL is correct so i dont know what is going wrong this is my C# code for the selection of the Combobox.
foreach (StandardDefinition standardDefinition in _StandardFields)
{
_wrapperSD = new WrapperStandardDefinition(Properties.Settings.Default.AppConnectionString,standardName,standardDefinition.Column_name);
_SD = _wrapperSD.GetStandardQuestion();
lstQuestions.Items.Add(string.Format("{0} ( {1} ) ", _standardDefinition, standardDefinition.Column_name));
}
public ISingleResult<StandardDefinition> GetStandardQuestion()
{
_SP = new StoredProcedures(_connection);
return _SP.GetExtendedProperty(_selectedStandard, _columnName);
}
This line here:
lstQuestions.Items.Add(string.Format("{0} ( {1} ) ", _standardDefinition, standardDefinition.Column_name));
.ToString() is implicitly being called on _standardDefinition when it is passed as a parameter to string.Format(). I believe this is what is giving you the class name.
You can either override the .ToString() method in the class if you want it to return something different. Or you can pass in the value you want, e.g. _standardDefinition.MyPropertyWithDesiredValue, rather than the object itself.
You are passing a custom StandardDefinition object to the Framework to display, but you haven't told it how to display it, so WPF uses the name of the type:
DAL.Entities.StandardDefinition
The quickest and easiest way to display something more meaningful is to simply override the object.ToString method, as that is what WPF will attempt to use by default. So if you were to do something like this...:
public override string ToString()
{
return string.Format("{0}: {1}", SomeProperty, SomeOtherProperty);
}
... your output could be something like this:
Some value: some other value
That would probably be fine for a text output, but another option to improve the display of these items would be for you to declare a DataTemplate which defines what each item should look like. You could do that something like this:
<DataTemplate DataType="{x:Type Entities:StandardDefinition}">
<!-- Define what the item should look like here -->
</DataTemplate>

How to add a value to a lookup field in sharepoint?

Hi I have two Lists in sharepoint 2007.
I have a lookup column in on list which looks the other field.
I want to use the sharepoint object model to add an item to the second list.
How to i set the lookup field value. (The value is already in the other list).?
SPListItem Employee = web.Lists["Employee"].Items.Add();
Employee["Name"] = account.Name;
Employee["Department"] = <lookup value must come here>
Employee.Update();
Lookup fields will contain a combination of the row's id and the value of the column to display, separated by :#, in your case that could be 1:#HumanResources or 12:#Engineering.
So to reference a lookup simply setting the id won't be enough, instead the above mentioned string needs to be set. Luckily SharePoint provides the class SPFieldLookupValue that does exactly this:
var department = web.Lists["Department"].GetItemById(1);
var employee = web.Lists["Employee"].Items.Add();
employee["Name"] = account.Name;
employee["Department"] = new SPFieldLookupValue(department.ID, department.Title);
employee.Update();

Combo Boxes With Multiple Columns

I've read that combo boxes cannot have multiple columns. Which leaves me a bit stuck since what I want to do is display one field from a table, but return the corresponding value from a second field in the same table i.e.
I'd like to show CustomerNames in the combo box, but when the user selects a name, the CustomerID field is returned instead. Whats the best work around for this?
Best way is to use ComboBoxes DisplayMember and ValueMember properties
set the ComboBox.DisplayMember to the property you want to display. Use ValueMember for property you want to return. Then you can use the ComboBox.SelectedValue to get the current/selected ValueMember
You don't need multiple columns to implement it.
class Member
{
public string Name{get;set;}
public string Address{get;set;}
public int ID{get;set;}
public string Description
{
get
{
return string.Format("{0}, {1}", Name, Address);
}
}
}
var members = new []
{
new Member(){ID = 1, Name = "John", Address = "Addr 1"},
new Member(){ID = 2, Name = "Mary", Address = "Addr 2"}
};
m_ComboBox.DataSource = members;
m_ComboBox.DisplayMember = "Description"
m_ComboBox.ValueMember = "ID";
now you can access seleceted ID
var selectedID = m_ComboBox.CelectedValue();
The value of the ComboBoxItem does not have to be the same as the Text, consider using the ID as the value.
You can achieve the desired behaviour by setting the DisplayMember and ValueMember properties of the ComboBox to "CustomerName" and "CustomerID" respectively.
Take a look at the ValueMember property. You should set this to CustomerID. After you bind to your combobox, the actual field displayed to the user will be the CustomerName, but when you want to get the value of 'CustomerName', it will return the CustomerID.
When you want to get the value of the combobox, simply reference the SelectedValue.
If you are adamant about displaying both of these in the combobox, there are some hackish ways of doing this but I would recommend reviewing your requirements again and seeing if it is absolutely necessary.
Alternatively, you can define KeyValuePair objects with your intended Ids and text fields. Feed them to the combo, since its Items property is a collection of objects. Then, for retrieval use a cast like
var x = (KeyValuePair)combo.Items[0];
and then acces then Key and Value properties of x.
You can use Tag property of ComboBoxItem to store the value.

Get Value from ASPxComboBox get value

I have combobox with 2 values, ID and Name. I need to get ID from selected item, and I don't know how.
ASPxComboBox1.SelectedItem.GetValue(ID);
Not working.
ASPxComboBox1.TextField = "Name"; //This is the displayMember
ASPxComboBox1.ValueField = "ID"; //This is the valueMember
ASPxComboBox1.ValueType = typeof(String);
ASPxComboBox1.DataSource = DataTableWithIDandNameColumns;
ASPxComboBox1.DataBind();
String theID = Convert.ToString(ASPxComboBox1.Value);//The column in the datasource that is specified by the ValueField property.
OR:
String theID = Convert.ToString(ASPxComboBox1.SelectedItem.GetValue("ID"));//Any column name in the datasource.
Also:
String theName = Convert.ToString(ASPxComboBox1.SelectedItem.GetValue("Name"));
Use ASPxComboBox.Value property.
A combobox can only have one value per item and this is retrieved in your case by:
ASPxComboBox1.Value
See here in the documentation.
Since the value returned will be of type object, you will need to cast this to the type originally set, e.g. String. Then you will be able to work with it.
Usually the problem, when the ASPxComboBox's SelectedItem / SelectedIndex is incorrect, occurs when the ASPxComboBox's ValueType http://documentation.devexpress.com/#AspNet/DevExpressWebASPxEditorsASPxComboBox_ValueTypetopic property is specified incorrectly.
Ensure that the ValueType is set, corresponding to the "Data Type Mappings (ADO.NET)" http://msdn.microsoft.com/en-us/library/cc716729.aspx table.

Categories