While populating a Textbox using a List. The Display method is as follows.
private void Display()
{
StringBuilder sb = new StringBuilder();
foreach (Player dude in _FootballRoster)
{
if (btnUSA.Checked == true)
{
sb.AppendLine("\r\nName: " + dude.getName() + " \r\n Team: " + dude.getTeam() + "\r\n Birthday: " + dude.getBirthday() + "\r\n Height(in):" + dude.getHeight() + "\r\n Weight(lbs): " + dude.getWeight() + "\r\n Salary(USD): " + dude.getSalary());
}
if (btnUSA.Checked == false)
{
sb.AppendLine("\r\nName: " + dude.getName() + " \r\n Team: " + dude.getTeam() + "\r\n Birthday: " + dude.getBirthday() + "\r\n Height(meters):" + (dude.getHeight()) / 39.3701 + "\r\n Weight(kg): " + (dude.getWeight()) / 2.20462 + "\r\n Salary(CD): " + (dude.getSalary()) / 1.31);
}
}
txtRosterLog.Text = sb.ToString();
}
While trying to implement a Sort method when you click btnName, I want "SORT BY: NAME" to appear at the top of the textbox but my current code puts it at the bottom of all the players.
Current Name Sort Code:
private void btnName_Click(object sender, EventArgs e)
{
_FootballRoster = _FootballRoster.OrderBy(dude => dude.Name).ToList();
Display();
txtRosterLog.AppendText("SORT BY: NAME ");
}
Any ideas? I've tried using txtRosterLog.Text.Insert(0, "SORT BY NAME)" but that didn't work either.
txtRosterLog.Text = "SORT BY: NAME \r\n" + txtRosterLog.Text;
txtRosterLog.Text.Insert(0, "SORT BY NAME)" would also work if you assign it back:
txtRosterLog.Text = txtRosterLog.Text.Insert(0, "SORT BY NAME");
I would go with String.Format as it is quite flexible and easly readable if you would like to make your string more fancy in future.
String s = String.Format("SORT BY: NAME \r\n {0}", txtRosterLog.Text);
Related
First, I apologize for the length of this, but it's all I knew when I started. Now I'm experimenting with the foreach, List<t> and TreeView classes to avoid repetition as recmomended by SO community.
The form will collect information via text boxes, allow attachments of files with file dialogs and collate all info into a neat HTML bodied email. We sell slabs.. and my original code looked a little like this:
private void PrepareReturnEmailTwoSlabs()
{
LoadSettings();
string Fname = Properties.Settings.Default.FabricatorName;
string Facc = Properties.Settings.Default.FabricatorAccountNo;
string Fadd1 = Properties.Settings.Default.FabricatorAddress1;
string Fadd2 = Properties.Settings.Default.FabricatorAddress2;
string Ftown = Properties.Settings.Default.FabricatorTown;
string Fcounty = Properties.Settings.Default.FabricatorCounty;
string Fpostcode = Properties.Settings.Default.FabricatorPostcode;
string Fphoneno = Properties.Settings.Default.FabricatorPhone;
string Femail = Properties.Settings.Default.FabricatorEmail;
string Fclient = Properties.Settings.Default.ClientManagerEmail;
string Fcentre = Properties.Settings.Default.CentreEmail;
string FQt = Properties.Settings.Default.QTEmail;
string Dateofinv = dateTimePicker1.Value.ToShortDateString();
string Inv = textBox13.Text;
string Material1 = textBox14.Text;
string Thick1 = comboBox8.SelectedValue.ToString();
string Batch1 = textBox44.Text;
string Reason1 = comboBox1.SelectedValue.ToString();
string Notes = textBox18.Text;
string Thick2 = comboBox7.SelectedValue.ToString();
string Material2 = textBox15.Text;
string Batch2 = textBox45.Text;
string Reason2 = comboBox2.SelectedValue.ToString();
if (Thick2 == null)
{
Thick2 = "not selected";
}
if (Material2 == null)
{
Material2 = "not selected ";
}
if (Batch2 == null)
{
Batch2 = "not selected ";
}
if (Reason2 == null)
{
Reason2 = "not selected ";
}
GenerateUniqueRefReturn();
//construct email
var message = new MimeMessage();
message.From.Add(new MailboxAddress("************", "***************"));
message.To.Add(new MailboxAddress("**********", "********"));
message.Subject = "Return" + " " + Returnid;
//different message bodies dependant on how many slabs are chosen
TextPart body2 = new TextPart("html")
{
Text = #"Please See Below Information" + "<br/>" +
"<h4>Return ID: " + " " + Returnid + "</h4>" + "<br/>" +
"<b>Fabricator Name:</b>" + " " + Fname + "<br/>" + Environment.NewLine +
"<b>Account Number:</b>" + " " + Facc + "<br/>" + Environment.NewLine +
"<b>Address Line 1:</b>" + " " + Fadd1 + "<br/>" + Environment.NewLine +
"<b>Address Line 2:</b>" + " " + Fadd2 + "<br/>" + Environment.NewLine +
"<b>Town:</b>" + " " + Ftown + "<br/> " + Environment.NewLine +
"<b>County:</b>" + " " + Fcounty + "<br/>" + Environment.NewLine +
"<b>Postcode:</b>" + " " + Fpostcode + "<br/>" + Environment.NewLine +
"<b>Phone:</b>" + " " + Fphoneno + "<br/>" + Environment.NewLine +
"<b>Email:</b>" + " " + Femail + "<br/>" + Environment.NewLine + "<br/>" +
"<br/>" +
"<b>Date Of Invoice: </b>" + " " + DoI + "<br/>" +
"<b>Invoice: </b>" + " " + Inv + "<br/>" +
"<b>Material Information:</b>" + "<br/>" +
//slab 1
"<b>Thickness: </b>" + " " + Thick1 + "mm" + "<br/>" +
"<b>Material Name: </b>" + " " + Material1 + "<br/>" +
"<b>Batch No: </b>" + " " + Batch1 + "<br/>" +
"<b>Reason for Return: </b>" + " " + Reason1 + "<br/>" + "<br/>" +
//slab 2
"<b>Thickness: </b>" + " " + Thick2 + "mm" + "<br/>" +
"<b>Material Name: </b>" + " " + Material2 + "<br/>" +
"<b>Batch No: </b>" + " " + Batch2 + "<br/>" +
"<b>Reason for Return: </b>" + " " + Reason2 + "<br/>" + "<br/>" +
"<br/>" +
"<b>Notes:" + " " + Notes
};
var builder = new BodyBuilder();
//check for return attachment and if found, assign attachment to message via bodybuilder
if (checkBox5.Checked)
{
builder.TextBody = body2.Text;
builder.HtmlBody = body2.Text;
builder.Attachments.Add(ReturnAttachment1);
message.Body = builder.ToMessageBody();
}
if (checkBox7.Checked)
{
builder.TextBody = body2.Text;
builder.HtmlBody = body2.Text;
builder.Attachments.Add(ReturnAttachment1);
builder.Attachments.Add(ReturnAttachment2);
message.Body = builder.ToMessageBody();
}
if (checkBox6.Checked)
{
builder.TextBody = body2.Text;
builder.HtmlBody = body2.Text;
builder.Attachments.Add(ReturnAttachment1);
builder.Attachments.Add(ReturnAttachment2);
builder.Attachments.Add(ReturnAttachment3);
message.Body = builder.ToMessageBody();
}
else
{
message.Body = body2;
}
//Connection to SMTP and Criteria to Send
using (var client = new SmtpClient())
{
// For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.Connect("smtp.gmail.com", 587, false);
// Note: only needed if the SMTP server requires authentication
client.Authenticate("***************#********.com", "*********");
client.Send(message);
client.Disconnect(true);
This code was repeated all the way up to five slabs. So now, I have a class:
{
public string Thickness { get; set; }
public string Material { get; set; }
public string Batch { get; set; }
public Slab(string Thick, string Mat, string Batchno)
{
Thickness = Thick;
Material = Mat;
Batch = Batchno;
}
}
A List that holds this object:
private void button1_Click(object sender, EventArgs e)
{
string t = comboBox1.SelectedValue.ToString();
string m = comboBox2.SelectedValue.ToString();
string b = textBox6.Text;
Slab S = new Slab(t, m, b);
allSlabs.Add(S);
PaintTree();
}
public void PaintTree()
{
int ParentIndex;
TreeSlabs.Nodes.Clear();
foreach (Slab slab in allSlabs)
{
TreeSlabs.BeginUpdate();
TreeSlabs.Nodes.Add("Slab" + " " + (allSlabs.IndexOf(slab) + 1).ToString());
ParentIndex = allSlabs.IndexOf(slab);
TreeSlabs.Nodes[ParentIndex].Nodes.Add("Thickness: " + $"{slab.Thickness}");
TreeSlabs.Nodes[ParentIndex].Nodes.Add("Material: " + $"{slab.Material}");
TreeSlabs.Nodes[ParentIndex].Nodes.Add("Batch: " + $"{slab.Batch}");
TreeSlabs.EndUpdate();
}
}
Now i want to create a foreach.. that iterates through each node.. and collects the info from the parent and its children foreach node, and somehow instantiate new HTML methods for each node..
Foreach Node:
Compose HTML Line - new HTML
Slab 1:
Thickness:
Material
Batch
Slab 2:... etc
If theres 8 nodes, it generates 8 of those bodies. i can think of ways.. but i KNOW they're defintely not the correct ways to go about it based on what ive read and seen out there.
Many Thanks
You don't need to iterate through the tree and try to reclaim the data you put into it from the List of Slabs; it would be simpler to enumerate the List:
By the way, some other tips:
don't beginupdate/endupdate inside the loop, do it outside
the Add method that adds a node to a tree returns the node it added; you don't have to find it again by index, just capture it var justAdded = rootnode.Add("parent node"); and then add your thickness etc to it justAdded.Nodes.Add("thickness..."). The only add command that doesn't return the added mode is the one that takes a treenode type object; it doesn't need to return it because you already have it
consider adding a method to your slab to return some html, to simplify things
you can tidy all that html up with some string interpolation like you did with your $"{slab.thickness}" etc
I am having a problem where the user enters his inputs into a text box (like a name). If the name is Jim Bob it will output like Jim System.Windows.Form.Label Bob System.Windows.Form.Label. I searched the properties tab and I am following along from the book but they do not have the same problem I have. I added some code below but I don't think it has anything to do with the problem.
string output;
output = textBoxPrefT.Text + ". " + textBoxFirstN + " " + textBoxMiddleN + " " + textBoxLastN;
labelOutput.Text = output;
You have to include .Text for all textboxes so it should look like this
string output;
output = textBoxPrefT.Text + ". " + textBoxFirstN.Text + " " + textBoxMiddleN.Text + " " + textBoxLastN.Text;
labelOutput.Text = output;
I'm doing a WCF service with GUI as client, however I have a problem with printing list of current items added. I have a code to add new entries to the list:
public bool Add_Data(Data sample)
{
container.Add(sample);
Console.WriteLine("New record added!");
return true;
}
And it's working, however when I'm trying to view added records with first try it works, however if I want to view it again list is adding same element. To show you how it works:
I'm adding new entry and I "print" list:
IMAGE CLICK [works how it should]
However I want to see it again, so I'm pressing same button in my form, and here is what happens:IMAGE CLICK as you can see, we have our list + additional same record, if I will press button again, I will have 3 same records.
Here is my "show records" code:
public string Show_Data()
{
Console.WriteLine("Printing records");
foreach (Data record in container)
{
string final_result = ("\nID: "+ + record.ID + " " + "product: " + record.product + " " + "category: " + record.category + " " + "price: " + record.price + " " + "quantity: " + record.quantity + " " + "\n ");
result += final_result;
}
return result;
}
Let me know if you know how to solve it.
You need to look into variable scope. You have result declared outside of the Show_Data() method. Each time the method is called you are doing result += final_result; which is adding to result. Try the code below and you will get different results.
public string Show_Data()
{
Console.WriteLine("Printing records");
var output = string.Empty;
foreach (Data record in container)
{
string final_result = ("\nID: "+ + record.ID + " " + "product: " + record.product + " " + "category: " + record.category + " " + "price: " + record.price + " " + "quantity: " + record.quantity + " " + "\n ");
output += final_result;
}
return output;
}
Also, I would consider using a string builder and string format as well.
public string Show_Data()
{
Console.WriteLine("Printing records");
var output = new StringBuilder();
foreach (Data record in container)
{
string final_result = string.Format("ID: {0} product: {1} category: {2} price: {3} quantity: {4}", record.ID, record.product, record.category, record.price, record.quantity);
// if using C# 6
// string final_result = string.Format($"ID: {record.ID} product: {record.product} category: {record.category} price: {record.price} quantity: {record.quantity)}";
output.AppendLine(final_result);
}
return output.ToString();
}
I'm trying to display content of the selected row into text box. This code doesn't work because it only add first selected item.
EDIT: This kind of work but my display look like this: ListViewSubItem: {a} ListViewSubItem: {b}
if (!string.IsNullOrEmpty(PC.SubItems[1].Text) && !string.IsNullOrEmpty(PC.SubItems[2].Text))
{
txtPc.Text = e.Item.SubItems[1].ToString()
+ " " + e.Item.SubItems[2].ToString();
}
EDIT: This works well:
private void SelectedItem(object sender, ListViewItemSelectionChangedEventArgs e)
{
if (tabSelectPage.SelectedTab != tabPage2)
txtSelected.Text = "User: " + e.Item.SubItems[1].Text +
"Pass" + e.Item.SubItems[2].Text;
else
txtSelected.Text = "URL: " + e.Item.SubItems[1].Text +
"User: " + e.Item.SubItems[2].Text +
"Pass" + e.Item.SubItems[3].Text;
}
This is how I have done it:
private void SelectedItem(object sender, ListViewItemSelectionChangedEventArgs e)
{
if (tabSelectPage.SelectedTab == tabPage1)
txtSelected.Text = " User Name: " + e.Item.SubItems[1].Text +
" Password: " + e.Item.SubItems[2].Text;
else if (tabSelectPage.SelectedTab == tabPage2)
txtSelected.Text = " URL: " + e.Item.SubItems[1].Text +
" User Name: " + e.Item.SubItems[2].Text +
" Password: " + e.Item.SubItems[3].Text;
else if (tabSelectPage.SelectedTab == tabPage3)
txtSelected.Text = " Software Name: " + e.Item.SubItems[1].Text +
" Serial Code: " + e.Item.SubItems[2].Text;
}
Use the ListViewItemSelectionChangedEventArgs.ItemIndex property.
i am trying to get the values of my controls like this:
function ConfirmWithUser()
{
var nodeText = '';
$('.mytreeview input[#type=checkbox]:checked').each(function() {
nodeText += $(this).next('a').text() + '\r';
});
var confirmationMessage;
confirmationMessage = "Please review the data before submitting:" + "\r"
+ "Sample Received Date: " + document.getElementById(received_dateTextbox).Value + "\r"
+ "Site of Ocurrence: " + document.getElementById(site_of_occurrenceTextBox).Value + "\r"
+ "Occurrence Date: " + document.getElementById(occurrence_dateTextBox).Value + "\r"
+ "Report Date: " + document.getElementById(report_byTextBox).Value + "\r"
+ "Specimen ID: " + document.getElementById(spec_idTextBox).Value + "\r"
+ "Batch ID: " + document.getElementById(batch_idTextBox).Value + "\r\n"
+ "Report Initiated By: " + document.getElementById(report_byTextBox).Value + "\r\n"
+ "Problem Identified By: " + $("input[#name=RadioButtonList1]:checked").val() + "\r\n"
+ "Problem List: " + nodeText;
HiddenFieldConfirmation.Value = confirmationMessage;
if (confirm(document.getElementById('HiddenFieldConfirmation').value) == true)
{ return true; }
else
{ return false; }
}
and the CONFIRM box is not firing at all! i do not get any pop up.
i tried to debug using firefox, and as soon as it go to this line:
confirmationMessage = "Please review the data before submitting:" + "\r"
+ "Sample Received Date: " + document.getElementById(re.......
it escapes out of the function
what am i doing wrong? how can i get the values of all the controls?
You need to use a lowercase "v" for value and quote your element ids. Eg:
document.getElementById("received_dateTextbox").value
Since it appears you are already using jQuery, you can make your code a little more concise. So document.getElementById("received_dateTextbox").value becomes:
$("#received_dateTextbox").val()
There is no variable named spec_idTextBox.
You probably want to pass a string literal.
Once you fix that, you need to use .value in lowercase
If you are using dynamic client ids, you have to render the ids inline or pass them to your function:
confirmationMessage = "Please review the data before submitting:" + "\r"
+ "Sample Received Date: " + document.getElementById('<% = received_dateTextbox.ClientID %>').value + "\r"
+ "Site of Ocurrence: " + document.getElementById('<% = site_of_occurrenceTextBox.ClientID %>').value + "\r"
+ "Occurrence Date: " + document.getElementById('<% = occurrence_dateTextBox.ClientID %>').value + "\r"
+ "Report Date: " + document.getElementById('<% = report_byTextBox.ClientID %>').value + "\r"
+ "Specimen ID: " + document.getElementById('<% = spec_idTextBox.ClientID %>').value + "\r"
+ "Batch ID: " + document.getElementById('<% = batch_idTextBox.ClientID %>').value + "\r\n"
+ "Report Initiated By: " + document.getElementById('<% = report_byTextBox.ClientID %>').value + "\r\n"
+ "Problem Identified By: " + $("input[#name=RadioButtonList1]:checked").val() + "\r\n"
+ "Problem List: " + nodeText;