public partial class Form1 : Form
{
public static Dictionary<string,string> contactList = new Dictionary<string,string>();
public Form1()
{
InitializeComponent();
Text = "My Telephone Directory";
}
private void txtAdd_Click(object sender, EventArgs e)
{
String name = txtName.Text;
String teleNo = txtTelephone.Text;
contactList.Add(name,teleNo);
txtContactList.Text = "Added " + name;
}
private void txtClear_Click(object sender, EventArgs e)
{
txtContactList.Text = " ";
}
private void txtList_Click(object sender, EventArgs e)
{
String contactLists="";
foreach (KeyValuePair<string,string> kvp in contactList)
{
contactLists += "Name: " + contactList.Keys.ToString()+ " Phone No: " + contactList.Values + Environment.NewLine;
}
txtContactList.Text = contactLists;
}
private void txtSearch_Click(object sender, EventArgs e)
{
String contactLists = "";
foreach (KeyValuePair<string, string> kvp in contactList)
{
contactLists += "Name: " + contactList.Keys.ToString() + " Phone No: " + contactList.Values + Environment.NewLine;
if (contactList.Keys.ToString() == txtName.Text)
{
contactLists += "Name: " + contactList.Keys.ToString() + " Phone No: " + contactList.Values.ToString() + Environment.NewLine;
}
txtContactList.Text = contactLists;
}
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
}
}
I cant enumerate the dictionary, see the txtList_Click eventhandler.
If I do what im doing, I get System.Collections.Generic.Dictionary2+KeyCollection[System.String,System.String] Phone No: System.Collections.Generic.Dictionary2+ValueCollection[System.String,System.String].
If I do contactList.Key like im supposed to I get System.Collections.Generic.Dictionary
You are calling the ToString() methods on the collection objects rather then the specific key and value pair. Try this:
foreach (KeyValuePair<string,string> kvp in contactList)
{
contactLists += "Name: " + kvp.Key + " Phone No: " + kvp.Value + Environment.NewLine;
}
Iterating the Dictionary and building the contactLists string
To iterate the Dictionary and build up a string, just use the KeyValuePair variable (kvp) that you've assigned in the foreach:
foreach (KeyValuePair<string, string> kvp in contactList)
{
contactLists += "Name: " + kvp.Key
+ " Phone No: " + kvp.Value + Environment.NewLine;
...
However, concatenating the string contactLists in a loop is inefficient. StringBuilder would help here, or, instead of the loop, you can simply project out each key value pair "string" with a Linq Select, and then Join them.
var contactLists =
string.Join(Environment.NewLine,
contactList.Select(cl => string.Format("Name: {0} Phone No: {1}",
cl.Key, cl.Value)));
Re searching the dictionary
One of the benefits of using a Dictionary (or HashSet) is that it offers indexed / keyed lookups, so you don't need to iterate the full collection to find an element by manual comparison of keys. So if you've keyed phone numbers by the person's name, this would be a more typical usage:
var searchPhone = contactList[txtName.Text];
To make this more robust, you'd want to check if the key exists first, e.g. with ContainsKey or TryGetValue:
string searchPhone;
if (contactList.TryGetValue(text.Name, out searchPhone))
... found, use searchPhone
else
... not found
Related
I have a function called "CreateReportForEachCompany" as following:
protected Dictionary<int, List<ReportObject>> CreateReportForEachCompany()
{
try
{
Dictionary<int, List<ReportObject>> dict = new Dictionary<int, List<ReportObject>>();
EnvironmentVariable.setEnvId((int)environmentEnum.mll);
//bakashot_tarif is a VIEW not a TABLE
DataTable dt = GeneralDbExecuterService.executeSqlSelectDataScript("select * from bakashot_tarif");
foreach (DataRow dr in dt.Rows)
{
var reportRow = FillObjectWithValues(dr);
int company_Id = dr.Field<int>("company_Id");
CreateDictionaryPairIfNotExist(dict, company_Id);
dict[company_Id].Add(reportRow);
}
return dict;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
now lets say I invoked it that way and got myself a dictionary with keys/values as needed.
var dictionary = CreateReportForEachCompany();
now.. I have another function named:
CreateCsvForEachCompany(Dictionary<int, List<ReportObject>> dict)
that TAKES the dictionary as parameter and creates few csvs based on the dictionary keys..
now those two functions above are executed on button click as following:
protected void ExecuteProgram(object sender, EventArgs e)
{
var dictionary = CreateReportForEachCompany();
CreateCsvForEachCompany(dictionary);
}
after that, I have a function named TransferSftpOnClick which meant to transfer file via SFTP (secure file transfer protocol ) into a designated location in the server:
void TransferSftpOnClick(Dictionary<int, List<ReportObject>> dict)
{
EnvironmentVariable.SetSubject(EnvironmentVariable.appSubjectEnum.btl);
string systemId = "MLL";
string fileType = "HIYUV-CHEVRA";
string chargeMonth = DateTime.Now.ToString("yyyyMM");
var fileCreationDate = DateTime.Now.ToString("yyyyMMdd");
string fileCreationTime = DateTime.Now.ToString("HHmmss");
string subject = EnvironmentVariable.appSubjectEnum.btl.ToString().ToUpper();
string location = EnvironmentVariable.getLocalFilePath() + #"\";
foreach (KeyValuePair<int, List<ReportObject>> entry in dict)
{
FtpUtil ftp = new FtpUtil();
int key = entry.Key;
string fileName = systemId + "-" + fileType + "-" + String.Format("{0:00000}", key) + "-" + chargeMonth + "-" + fileCreationDate + "-" + fileCreationTime + ".CSV";
**ftp.saveFileToFtp(location, key.ToString(), fileName, subject);**
}
}
I want my function to recognize the dictionary that is executed in function "ExecuteProgram()"
And I want to trigger onClick on TransferSftpOnClick that will just transfer me the files to the designated location.
how can I achieve that? is it even worth doing?
or should I just do this:
FtpUtil ftp = new FtpUtil();
ftp.saveFileToFtp(location, key.ToString(), fileName, subject);
under the CreateCsvPerCompany to avoid that mess?
hope I was clear, thanks
private void btnAssemble_Click(object sender, EventArgs e)
{
txtAssembled.Text = (cboTitle.Text + txtFirstName.Text[0] + txtMiddle.Text + txtLastName.Text + "\r\n" +txtStreet.Text + "\r\n"+ cboCity.Text);
}
I'm trying to get 1 character white space inbetween cboTitle.Text, txtFirname.Text, txtMiddle.Text, and txtLastName, but they all output the information together, but I want them spaced evenly. what do I need to do? thanks in advance.
I'm going to post some other code thats below the one above in my project, just in case it might be relevant.
string AssembleText(string Title, string FirstName, string MiddleInitial, string LastName, string AddressLines, string City )
{
string Result = "";
Result += Title + " ";
Result += FirstName.Substring(0, 2) + " ";
// Only append middle initial if it is entered
if (MiddleInitial != "")
{
Result += MiddleInitial + " ";
}
Result += LastName + "\r\n";
// Only append items from the multiline address box
// if they are entered
if ( AddressLines != "")
{
Result += AddressLines + "\r\n";
}
//if (AddressLines.Length > 0 && AddressLines.ToString() != "")
//{
// Result += AddressLines + "\r\n";
//}
Result += City;
return Result;
}
}
}
If you just want a space between those specific fields in btnAssemble_Click, you can just insert them like this:
string myStr = foo + " " + bar + " " + baz;
So your first function would be modified to read:
private void btnAssemble_Click(object sender, EventArgs e)
{
txtAssembled.Text = (cboTitle.Text + " " + txtFirstName.Text[0] + " " + txtMiddle.Text + " " + txtLastName.Text + "\r\n" + txtStreet.Text + "\r\n" + cboCity.Text);
}
A few other comments:
It's not clear to me what the AssembleText() function you posted has to do with this. I am confused though, as I see a few lines appending spaces at the end just like I mentioned above.
Using the String.Format() function may make this code easier to read and maintain.
Using Environment.NewLine instead of "\r\n" will make the string contain the newline character defined for that specific environment.
Using a StringBuilder object may be faster over concatenation when building strings inside of a loop (which may not apply here).
Using String.format() should feet the bill. It also make your code easy to read.
txt.assembled.text = String.Format("{0} {1} {2} {3}",
cboTitle.Text,
txtFirstName.Text[0],
txtMiddle.Text,
txtLastName.Text
);
It would be like this
private void btnAssemble_Click(object sender, EventArgs e)
{
txtAssembled.Text = (cboTitle.Text + " " + txtFirstName.Text[0] + " " +txtMiddle.Text + " " + txtLastName.Text + "\r\n" +txtStreet.Text + "\r\n"+ cboCity.Text);
}
It seems that you want String.Join; whenever you want to combine strings with a delimiter, say, " " (space) all you need is to put
String combined = String.Join(" ",
cboTitle.Text,
txtFirstName.Text[0],
txtMiddle.Text,
txtLastName.Text);
Complete implementation (joining by space and new line) could be
txtAssembled.Text = String.Join(Environment.NewLine,
String.Join(" ",
cboTitle.Text,
txtFirstName.Text[0],
txtMiddle.Text,
txtLastName.Text),
txtStreet.Text,
cboCity.Text);
I have a static dictionary that i create globally. I declare it like this =>
static Dictionary<int, Artikels> dicArtikels = new Dictionary<int, Artikels>();
Artikels is a class i have created to store the products.
for (int rijenTeller = 0; rijenTeller < aantalRijen; rijenTeller++)
{
Artikels artikel = new Artikels();
if (dicArtikels.ContainsKey(rijenTeller))
{
artikel = dicArtikels[rijenTeller];
}
else
{
dicArtikels.Add(rijenTeller, artikel);
}
artikel.naam = txtNameInstance.Text;
artikel.prijs = txtPriceInstance.Text;
dicArtikels[rijenTeller] = artikel;
artikel = null;
}
Well when i print the output with a button like below it's always showing the value of the last instance. That't not what i want. I want the value of the seperate instances but they are always getting the same value. =>
protected void Button3_Click(object sender, EventArgs e)
{
try
{
Artikels artikel = new Artikels();
artikel = dicArtikels[0];
Response.Write(artikel.naam.ToString() + " -- " + artikel.prijsExclBTW.ToString());
artikel = dicArtikels[3];
Response.Write(artikel.naam.ToString() + " -- " + artikel.prijsExclBTW.ToString());
artikel = dicArtikels[1];
Response.Write(artikel.naam.ToString() + " -- " + artikel.prijsExclBTW.ToString());
artikel = dicArtikels[2];
Response.Write(artikel.naam.ToString() + " -- " + artikel.prijsExclBTW.ToString());
}
catch (Exception ex)
{
Response.Write("Foutbericht Artikelchangedssssssss: " + ex.Message);
}
}
I am trying to access a dictionary nested inside another dictionary.
The code I wrote is:
foreach (var entry in source)
{
int i = 0;
str = str + i + ": key: " + entry.Key + "; value = " + entry.Value +"; ";
// do something with entry.Value or entry.Key
}
and for some elements the value is System.Collections.Generic.Dictionary`2[System.String,System.Object]
I would like to access this dictionary when the inner value has a given value, as "Department".
Any idea on how to do it?
I would like to access this dictionary when the inner key has a given
value, as "Department"
Assuming you have a dictionary like this:
var source = new Dictionary<string, Dictionary<String, Object>>();
foreach (var outerEntry in source)
{
foreach (var innerEntry in outerEntry.Value)
{
if(innerEntry.Key == "Department")
{
// do something
Console.WriteLine("Key:{0} Value:{1}", innerEntry.Key, innerEntry.Value);
}
}
}
If the Value is a dictionary you could loop through the underlying dictionary keys:
foreach (var entry in source)
{
int i = 0;
str = str + i + ": key: " + entry.Key + "; value = "
if (entry.Value is IDictionary)
}
str = str + " { ";
foreach (var innerentry in (entry.Key as IDictionary))
{
str = str + innerentry.Key + "; value = " + innerentry.Value +"; ";
}
str = str + " } ";
}
else
str = str + entry.Value +"; ";
// do something with entry.Value or entry.Key
}
I need to grab all the FIELD and VALUES from a POST.
I have the follow which only return the FIELDs but no Values.
NameValueCollection authForm = Request.Form;
String[] a = authForm.AllKeys;
for (i = 0; i < a.Length; i++)
{
frm += ("Form: " + a[i] + " : " + "<br>");
}
Response.Write(frm);
What can I add this the frm string to show the VALUES ?
UPDATE:
I used the initial code of
NameValueCollection authForm = Request.Form;
foreach (string key in authForm.AllKeys)
{
frm += ("Key: " + key + ", Value: " + authForm[key] + "<br/>");
}
which worked great. I will try the new variation below.
NameValueCollection authForm = Request.Form;
StringBuilder sb = new StringBuilder();
foreach (string key in authForm.AllKeys)
{
sb.AppendFormat(
"Key: {0}, Value: {1}<br/>",
HttpUtility.HtmlEncode(key),
HttpUtility.HtmlEncode(authForm[key])
);
}
Response.Write(sb.ToString());