C#: Using String Value as name of Object Reference - c#

At the moment, I have multiple textblocks which I want to access according to the name of the string. Look at the example below:
TextBlock test1 = new TextBlock();
TextBlock test2 = new TextBlock();
TextBlock test3 = new TextBlock();
TextBlock test4 = new TextBlock();
public static void changeValues()
{
string name = "test";
for (int i = 1; i < 5; i++)
{
[name + i].Text = "Wow";
}
}
As you can see, I am trying to access text1, text2, etc. The reason I am doing this is because the value of "name" could change at any time so I can re-use this code. I can also make "i < 5" be "i < number" and have the method take an int as one of the arguments. The problem of course is that this won't actually work. I need the string name to be a reference to the TextBlock that the name gives. Any help is appreciated!

#PetSerAl is saying:
var yourBlocks = new TextBlock[]
{
new TextBlock(),
new TextBlock(),
new TextBlock(),
new TextBlock()
};
foreach (var block in yourBlocks)
{
block.Text = "Wow";
}

How about Dictionary?
Dictionary<string, string> myDictionary=
new Dictionary<string, TextBlock>();
myDictionary.Add("name1", mytextBlock1);
myDictionary.Add("name2", mytextBlock2);
myDictionary["name1"] = new TextBlock();
var tBlock = myDictionary["name2"];
Detail here

Related

Expander Control - Read txt-Files in C# (WindowsForms)

I‘m trying to add the second .txt file (book2) into Text Expander control, unfortunately without success.
public Form1()
{
InitializeComponent();
CreateAccordion();
}
private void CreateAccordion(string book1)
{
Accordion accordion = new Accordion();
accordion.Size = new Size(400, 350);
accordion.Left = 10;
Expander expander1 = new Expander();
expander1.BorderStyle = BorderStyle.FixedSingle;
ExpanderHelper.CreateLabelHeader(expander1, "Book1", SystemColors.ActiveBorder);
CreateContentLabel(expander1, book1, 140);
accordion.Add(expander1);
Expander expander2 = new Expander();
expander2.BorderStyle = BorderStyle.FixedSingle;
ExpanderHelper.CreateLabelHeader(expander2, "Book2", SystemColors.ActiveBorder);
CreateContentLabel(expander2, "book2", 120);
accordion.Add(expander2);
this.Controls.Add(accordion);
}
The following code reads only a single txt.file. Can anyone help me please?
private void CreateAccordion()
{
ReadTxtFiles();
}
private void ReadTxtFiles()
{
string path = #"C:\..\..\READBOOKS";
string[] files = new string[] { "book1.txt", "book2.txt" };
foreach (string file in files)
{
string fullPath = Path.Combine(path, file);
string booktxt = File.ReadAllText(fullPath);
string book1 = booktxt;
CreateAccordion(book1);
}
}
I‘m trying to add the second .txt file (book2) into Text Expander control, unfortunately without success.
The main reason behind this is because you're only passing the string from your first book, you'll need to pass all of the text.
private void ReadTxtFiles()
{
string path = #"C:\..\..\READBOOKS";
string[] files = new string[] { "book1.txt", "book2.txt" };
List<string> books = new List<string>();
foreach (string file in files)
{
string fullPath = Path.Combine(path, file);
string booktxt = File.ReadAllText(fullPath);
books.Add(booktxt);
}
CreateAccordion(books);
}
Change the signature of CreateAccordion:
private void CreateAccordion(List<string) books)
{
Accordion accordion = new Accordion();
accordion.Size = new Size(400, 350);
accordion.Left = 10;
Expander expander1 = new Expander();
expander1.BorderStyle = BorderStyle.FixedSingle;
ExpanderHelper.CreateLabelHeader(expander1, "Book1", SystemColors.ActiveBorder);
CreateContentLabel(expander1, books[0], 140);
accordion.Add(expander1);
Expander expander2 = new Expander();
expander2.BorderStyle = BorderStyle.FixedSingle;
ExpanderHelper.CreateLabelHeader(expander2, "Book2", SystemColors.ActiveBorder);
CreateContentLabel(expander2, books[1], 120);
accordion.Add(expander2);
this.Controls.Add(accordion);
}
Please note that I'm accessing index's here, you may want to check that the index exist before trying to access it. Also there's more way's than this, but should give you a better understanding to accomplish this.

how to add dynamic array of item in ExpandoObject Xamarin.forms

i want to add dynamically selected items in ExpandoObject then print it in the form of json value. if i selected 2values, it is printing only the last value 2times.My problem is whatever im selecting it prints last value only.
My code:
Declaration
dynamic output = new List<dynamic>();
dynamic foo = new ExpandoObject();
List<int> selected = new List<int>();
switch toggle function:
private void Switch_Toggled(object sender, ToggledEventArgs e)
{
var switch1 = (Switch)sender;
var human = (Human)switch1.BindingContext;
var id = human.retail_modified_item_id;
var name = human.name;
var old_price = human.old_price;
var new_price = human.new_price;
if (switch1.IsToggled)
{
if (!selected.Contains(id))
{
selected.Add(id);
foo.id = id;
foo.name = name;
foo.old_price=old_price;
foo.new_price=new_price;
output.Add(foo);
}
}
else
{
if (selected.Contains(id)) selected.Remove(id);
}
}
Printing Json value ;
string json = Newtonsoft.Json.JsonConvert.SerializeObject(output);
Debug.WriteLine(json);
My output is:
[{"id":1000739,"name":"Hashbrowns","old_price":0.99,"new_price":8.5},{"id":1000739,"name":"Hashbrowns","old_price":0.99,"new_price":8.5}]
if i selected 2values, it is printing only the last value 2times.
dynamic foo = new ExpandoObject();
you declare global variables here,so the second time you call the following code, you are reassuming the first foo and adding it again, so there are two identical items in the output List.
foo.id = id;
foo.name = name;
foo.old_price=old_price;
foo.new_price=new_price;
output.Add(foo);
you could change like this :
if (!selected.Contains(id))
{
selected.Add(id);
dynamic foo = new ExpandoObject(); // local variables
foo.id = id;
foo.name = name;
foo.old_price=old_price;
foo.new_price=new_price;
output.Add(foo);
}

Passing multiple line items with GP webservice

Below is the code I'm working with to pass multiple line items to create sales order through GP Web service. I can pass single Line Item without any problem , but when I pass multiple Items it is only taking the last one. The array has around 5 Item ID and I'm passing fixed Quantity as 15, Need to make both dynamic. But for the testing purpose I'm trying like this. I know the problem with the creation/initialization of some web service objects. As novice to the entire set of things I couldn't find the exact problem.
C# Code
CompanyKey companyKey;
Context context;
SalesOrder salesOrder;
SalesDocumentTypeKey salesOrderType;
CustomerKey customerKey;
BatchKey batchKey;
// SalesOrderLine salesOrderLine;
ItemKey orderedItem;
Quantity orderedAmount;
Policy salesOrderCreatePolicy;
DynamicsGPClient wsDynamicsGP = new DynamicsGPClient();
wsDynamicsGP.ClientCredentials.Windows.ClientCredential.UserName = "Admin";
wsDynamicsGP.ClientCredentials.Windows.ClientCredential.Password = "pass";
wsDynamicsGP.ClientCredentials.Windows.ClientCredential.Domain = "Gp";
System.ServiceModel.WSHttpBinding binding;
binding = new System.ServiceModel.WSHttpBinding(System.ServiceModel.SecurityMode.None);
context = new Context();
companyKey = new CompanyKey();
companyKey.Id = (1);
context.OrganizationKey = (OrganizationKey)companyKey;
salesOrder = new SalesOrder();
salesOrderType = new SalesDocumentTypeKey();
salesOrderType.Type = SalesDocumentType.Order;
salesOrder.DocumentTypeKey = salesOrderType;
customerKey = new CustomerKey();
customerKey.Id = "121001";
salesOrder.CustomerKey = customerKey;
batchKey = new BatchKey();
batchKey.Id = "RMS";
salesOrder.BatchKey = batchKey;
// SalesOrderLine[] orders = new SalesOrderLine[6];
SalesOrderLine[] lines = { };
for (int i = 1; i < 5; i++)
{
SalesOrderLine salesOrderLine = new SalesOrderLine();
orderedItem = new ItemKey();
orderedItem.Id = Arr[i].ToString();
salesOrderLine.ItemKey = orderedItem;
orderedAmount = new Quantity();
orderedAmount.Value = 15;
salesOrderLine.Quantity = orderedAmount;
lines = new SalesOrderLine[] { salesOrderLine };
MessageBox.Show(lines.Count().ToString());
}
salesOrder.Lines = lines;
//salesOrder.Lines = orders;
salesOrderCreatePolicy = wsDynamicsGP.GetPolicyByOperation("CreateSalesOrder", context);
wsDynamicsGP.CreateSalesOrder(salesOrder, context, salesOrderCreatePolicy);
if (wsDynamicsGP.State != CommunicationState.Faulted)
{
wsDynamicsGP.Close();
}
MessageBox.Show("Success");
lines = new SalesOrderLine[] { salesOrderLine }; will recreate the lines array object each time meaning you loose any previously added objects. Effectively only the final object in the loop is actually added.
Try using a List<T> like so:
SalesOrderLine[] lines = { }; Becomes List<SalesOrderLine> lines = new List<SalesOrderLine>();
lines = new SalesOrderLine[] { salesOrderLine }; Becomes: lines.Add(salesOrderLine);
If its important you end up with an array as the input:
salesOrder.Lines = lines; Becomes: salesOrder.Lines = lines.ToArray();

How to customize a tooltip for each individual datapoint in a wpf toolkit lineseries chart?

I have seen several questions about doing a custom tooltip for a single line series.
I need a custom tool-tip for each data-point. I would like to add more to the tool-tip than just the dependent value path and the independent value path.
Example I have 2 data points on the same line one with a value(Y-axis)
of 2, date(x-axis) of 4/28/2016, and configuration of A. The other has
a value of 3, date of 4/29/2016, and configuration of B.
How would I also show the configurations? This is all done in code behind because I have a dynamic number of lineseries. So I can't just assign a style to each lineseries in the xaml.
var MyLineSeries = new LineSeries();
lMyLineSeries.DependentValuePath = "Y";
lMyLineSeries.IndependentValuePath = "X";
lMyLineSeries.DataPointStyle = lToolTipDataPointStyle;
This is my code for creating the tool tip style.
var lToolTipDataPointStyle = new Style(typeof(LineDataPoint));
var lTemplate = new ControlTemplate(typeof(LineDataPoint));
var lGridElement = new FrameworkElementFactory(typeof(Border));
//Tooltip
var lStackPanel = new StackPanel();
var lValueContentControl = new ContentControl();
lValueContentControl.SetBinding(ContentControl.ContentProperty, new Binding(myLineSeries.DependentValuePath));
lValueContentControl.ContentStringFormat = "Value: {0}";
var lConfigurationContentControl = new ContentControl();
lConfigurationContentControl.SetBinding(ContentControl.ContentProperty, new Binding())//This is what Idk what to bind to???
lConfigurationContentControl.ContentStringFormat = "Configuration: {0}";
lStackPanel.Children.Add(lValueContentControl);
lStackPanel.Children.Add(lConfigurationContentControl);
lGridElement.SetValue(ToolTipService.ToolTipProperty, lStackPanel);
var lEllipseElement = new FrameworkElementFactory(typeof(Ellipse));
lEllipseElement.SetValue(Ellipse.StrokeThicknessProperty, new TemplateBindingExtension(Border.BorderThicknessProperty));
lEllipseElement.SetValue(Ellipse.StrokeProperty, new TemplateBindingExtension(Border.BorderBrushProperty));
lEllipseElement.SetValue(Ellipse.FillProperty, new TemplateBindingExtension(Grid.BackgroundProperty));
lGridElement.AppendChild(lEllipseElement);
lTemplate.VisualTree = lGridElement;
var lTemplateSetter = new Setter();
lTemplateSetter.Property = LineDataPoint.TemplateProperty;
lTemplateSetter.Value = lTemplate;
lToolTipDataPointStyle.Setters.Add(lTemplateSetter);
return lToolTipDataPointStyle;
I figured it out by using the Tag on the Line series.
myLineSeries.Tag = "Configuration";
var lConfigurationContentControl = new ContentControl();
lConfigurationContentControl.SetBinding(ContentControl.ContentProperty, new Binding(myLineSeries.Tag.ToString()))
lConfigurationContentControl.ContentStringFormat = "Configuration: {0}";

datetime display issue from webservice

Im having diffculty with datetime when its displayed client side from my rest web service, my client side wpf app code looks like this:
public MainWindow()
{
InitializeComponent();
string uriGroups = "http://localhost:8000/Service/Student";
XDocument xDoc = XDocument.Load(uriGroups);
foreach(var node in xDoc.Descendants("Student"))
{
GroupBox groupbox = new GroupBox();
groupbox.Header = String.Format(node.Element("StudentID").Value);
groupbox.Width = 100;
groupbox.Height = 100;
groupbox.Margin = new Thickness(2);
TextBlock textBlock = new TextBlock();
textBlock.Text = String.Format(node.Element("FirstName").Value + " " + (node.Element("LastName").Value));
textBlock.TextAlignment = TextAlignment.Center;
TextBlock textBlock1 = new TextBlock();
textBlock1.Text = String.Format(node.Element("TimeAdded").Value);
textBlock1.TextAlignment = TextAlignment.Center;
textBlock1.VerticalAlignment = VerticalAlignment.Bottom;
StackPanel stackPanel = new StackPanel();
stackPanel.Children.Add(groupbox);
stackPanel.Children.Add(textBlock);
stackPanel.Children.Add(textBlock1);
stackPanel.Margin = new Thickness(10);
MainArea.Children.Add(stackPanel);
}
}
And my service looks like this:
public class Student
{
....
public DateTime TimeAdded;
public string TimeAddedString
{
get
{
return this.TimeAdded.ToString("dd/MM/yyyy hh:mm:ss");
}
}
But the output looks like this:
Is there a way on my client side app code to truncate this or reformat it?
You can cast it to a DateTime and then use String.Format
Here is an example with one format you could use:
String.Format("{0:M/d/yyyy}", ((DateTime)node.Element("TimeAdded").Value))
You can also use DateTime.ToString(FORMAT)
((DateTime)node.Element("TimeAdded").Value).ToString("d");
I have made an assumption that .Value returns an object, but if it returns a DateTime then you can drop the casts.
If you are getting a string into your client, then you will need to use DateTime.Parse
(DateTime.Parse(node.Element("TimeAdded").Value)).ToString("d");
String.Format("{0:M/d/yyyy}", DateTime.Parse(node.Element("TimeAdded").Value))
You are using TimeAdded...but I think you should be using TimeAddedString
textBlock1.Text = String.Format(node.Element("TimeAdded").Value);
Should be
textBlock1.Text = String.Format(node.Element("TimeAddedString").Value);
I believe

Categories

Resources