Okay so I'm trying to display multiple values in hashtable through my button. But it keeps on showing me the first value but not the others.
public Form1()
{
InitializeComponent();
}
Hashtable Info = new Hashtable();
private void button1_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
string b = textBox2.Text;
Info.Add(a,b);
label4.Text = a + " " + b;
}
private void button3_Click(object sender, EventArgs e)
{
foreach (DictionaryEntry DE in Info)
{
label4.Text = ""+ DE.Key +DE.Value; //this only shows the first added value. How do I show the remaining values?
}
}
This is because each iteration of the loop replaces the previous value in the text. You can fix this by clearing out the text before going into the loop, and using += instead of =:
label4.Text += " "+ DE.Key +DE.Value
A better approach would be to use string.Join for this:
private void button3_Click(object sender, EventArgs e) {
label4.Text = string.Join(
", "
, Info.Select(p => string.Format("{0}-{1}", p.Key, p.Value))
);
}
I recommend you don't keep changing label4.Text in the loop, but build a string in the loop and change it once at the end. Something like:
StringBuilder allEntries = new StringBuilder();
foreach (DictionaryEntry DE in Info)
{
allEntries.Append(DE.Key);
allEntries.Append(DE.Value);
}
label4.Text = allEntries.ToString();
[I edited an earlier version of the code that didn't compile.]
KC
Related
I'm trying to make that theirs a check if a textbox is empty, it wont pass the information on multiple textboxes on a button press, example:
private void button1_Click(object sender, EventArgs e)
{
if (this.Controls.OfType<TextBox>().Any(t => string.IsNullOrWhiteSpace(t.Text)))
{
// what can i put here to exclude multiple
}
else
{
//if any of thouse are empty i dont want them to do this but if they are not empty i do want
lablCinnamonset.Text = textBox1.Text;
lablMallardset.Text = textBox2.Text;
lablAxisdeerSet.Text = textBox3.Text;
lablBlackbuckSet.Text = textBox4.Text;
lablMuledeerSet.Text = textBox5.Text;
lablReddeerSet.Text = textBox6.Text;
lablPumaSet.Text = textBox7.Text;
lablWaterbuffaloSet.Text = textBox8.Text;
lablJackrabbitSet.Text = textBox9.Text;
lablCoyoteSet.Text = textBox10.Text;
lablWhitetailSet.Text = textBox11.Text;
lablBlacktailSet.Text = textBox12.Text;
lablBlackbearSet.Text = textBox13.Text;
lablRooseveltSet.Text = textBox14.Text;
lablMooseSet.Text = textBox15.Text;
}
I don't want to do, a if statement for each textbox, it has to be a better way.
Thank you guys
Why don't just extract a method?
private static void AssignIfNotEmpty(Control target, Control source) {
if (!string.IsNullOrWhiteSpace(source.Text))
target.Text = source.Text;
}
Then use it
private void button1_Click(object sender, EventArgs e) {
AssignIfNotEmpty(lablCinnamonset, textBox1);
AssignIfNotEmpty(lablMallardset, textBox2);
AssignIfNotEmpty(lablAxisdeerSet, textBox3);
AssignIfNotEmpty(lablBlackbuckSet, textBox4);
AssignIfNotEmpty(lablMuledeerSet, textBox5);
AssignIfNotEmpty(lablReddeerSet, textBox6);
AssignIfNotEmpty(lablPumaSet, textBox7);
AssignIfNotEmpty(lablWaterbuffaloSet, textBox8);
AssignIfNotEmpty(lablJackrabbitSet, textBox9);
AssignIfNotEmpty(lablCoyoteSet, textBox10);
AssignIfNotEmpty(lablWhitetailSet, textBox11);
AssignIfNotEmpty(lablBlacktailSet, textBox12);
AssignIfNotEmpty(lablBlackbearSet, textBox13);
AssignIfNotEmpty(lablRooseveltSet, textBox14);
AssignIfNotEmpty(lablMooseSet, textBox15);
}
You may want to organize your controls e.g.
public partial class MyForm : Form {
private Dictionary<Label, TextBox> m_Correspondence =
new Dictionary<Label, TextBox>();
public MyForm() {
InitializeComponent();
m_Correspondence.Add(lablCinnamonset, textBox1);
m_Correspondence.Add(lablMallardset, textBox2);
...
m_Correspondence.Add(lablMooseSet, textBox15);
}
In this case button1_Click will be very simple:
private void button1_Click(object sender, EventArgs e) {
foreach (var pair in m_Correspondence)
AssignIfNotEmpty(pair.Key, pair.Value);
}
Supposing you can change the names of various "labl..." with something like "labl1", "labl2" or mapping them in some way (maybe using a Dictionary), then you can use the
FindName function.
Example:
for(int i=1; i<16; i++){
if( (TextBox)this.FindName("textBox" + i.ToString()).Text != ""){
//Here you can do what you want
}
}
Reference here: https://learn.microsoft.com/it-it/dotnet/api/system.windows.frameworkelement.findname?view=netframework-4.8
I need to accept more than one value from the same textbox and store it into an arrya . I need something close to the below code :
string[] countries = new string[3];
private void accept_Click(object sender, EventArgs e)
{
countries[0] = textBox1.Text+" 1 ";
countries[1] = textBox1.Text + " 2 ";
countries[2] = textBox1.Text + " 3 ";
}
private void finish_Click(object sender, EventArgs e)
{
foreach (string coun in countries)
MessageBox.Show("You have entered " + coun);}
}
}
How do you split the different countries?
If you split it on each space you can do it like this:
string[] countries = textBox1.Text.Split(null);
If that is not a good solution maybe try and explain the expected output.
You can simply use a multiline textbox and split the input on newlines:
var countries = countriesTextBox.Text.Split(Environment.NewLine);
Why not just use a list? The following code will add the country's name entered in the textbox to the List<string> every time you click the accept button.
var countries = new List<string>();
private void accept_Click(object sender, EventArgs e)
{
countries.Add(textBox1.Text);
}
private void finish_Click(object sender, EventArgs e)
{
foreach (string coun in countries)
MessageBox.Show("You have entered " + coun);
}
If you want to allow the user to enter multiple countries at once, the following will work if you put a comma in between each country name when entering them into the textbox:
var countries = new List<string>();
private void accept_Click(object sender, EventArgs e)
{
var input = textBox1.Text.Split(',');
countries.AddRange(input);
}
private void finish_Click(object sender, EventArgs e)
{
foreach (string coun in countries)
MessageBox.Show("You have entered " + coun);
}
This is for my timer
private void timer_tick(object sender, EventArgs e)
{
string timeNow = "";
timeNow = DateTime.Now.ToString("hh:mm") + " " + DateTime.Now.ToString("tt");
medicineAlarm();
}
private void medicineAlarm()
{
DataTable dt = new DataTable();
dt = database.getSchedule();
string AMTime;
string PMTime;
string NNTime;
foreach (DataRow row in dt.Rows)
{
AMTime = row["AMIntake"].ToString();
PMTime = row["PMIntake"].ToString();
NNTime = row["NNIntake"].ToString();
if (AMTime == timeNow || PMTime == timeNow || NNTime == timeNow)
{
MessageBox.Show("Drink Medicine");
}
}
}
How can i show the message even if i am running the program? Hope you can help me. This is inside my form_load
private void Form1_Load(object sender, EventArgs e)
{
timer.Interval = 1000;
timer.Tick += new EventHandler(this.timer_tick);
timer.Start();
The medicineAlarm() method does not have any access to the timeNowvariable that you are setting up in the timer_tick() event handler. I suggest you pass the variable in:
private void timer_tick(object sender, EventArgs e)
{
string timeNow = DateTime.Now.ToString("hh:mm") + " " + DateTime.Now.ToString("tt");
medicineAlarm(timeNow);
}
private void medicineAlarm(string timeNow)
{
DataTable dt = database.getSchedule();
foreach (DataRow row in dt.Rows)
{
foreach(var label in new [] {"AM", "PM", "NN"})
if (row[label + "Intake"].ToString() == timeNow)
{
MessageBox.Show("Drink Medicine");
return;
}
}
}
I don't think your code compiles at all since the variable string timeNow = ""; is declared in event handler and doesn't exists in your method body. You may want to pass it to the method like
private void medicineAlarm(string timeNow)
{
You then call it
private void timer_tick(object sender, EventArgs e)
{
string timeNow = "";
timeNow = DateTime.Now.ToString("hh:mm") + " " + DateTime.Now.ToString("tt");
medicineAlarm(timeNow);
}
I wrote a few code line in c# to iterate through a list, but i print in the textbox only the last one. the code that i wrote:
//For instantiation
Account account = new Account(0,"","", 0);
//A list for class Account
List<Account> listAccount = new List<Account>();
//Button for adding new Customer
private void button1_Click(object sender, EventArgs e)
{
account.CustomerID = int.Parse(customerIdTxt.Text);
account.CustomerFullName = customerNameTxt.Text;
account.CustomerAddress = customerAddrTxt.Text;
listAccount.Add(account);
}
//For printing the Customer's detailes in textbox
private void button6_Click(object sender, EventArgs e)
{
string showCustDetailes = "";
for(int i=0;i<listAccount.Count;i++)
{
showCustDetailes+=
"Customer ID : " + listAccount[i].CustomerID + Environment.NewLine +
"Customer Name : " + listAccount[i].CustomerFullName + Environment.NewLine +
"Customer Address : " + listAccount[i].CustomerAddress + Environment.NewLine +
"---------------------------------------------------" + Environment.NewLine;
}
viewDetailesTxt.Text = showCustDetailes;
}
can anyone help me how can i print the whole customers list
There's nothing wrong with the code that loops over the list (apart from not using foreach()). If you really only see one account, the problem is in displaying: make your textbox bigger or give it scrollbars.
Also, you're editing the same instance of account every time, so you're filling your list with multiple references to the same account. You must use new Account to instantiate a new one for every "button 1" click:
private void button1_Click(object sender, EventArgs e)
{
Account account = new Account(0,"","", 0);
// ...
listAccount.Add(account);
}
List<Account> listAccount = new List<Account>();
private void button1_Click(object sender, EventArgs e)
{
var account = new Account {
CustomerID = int.Parse(customerIdTxt.Text),
CustomerFullName = customerNameTxt.Text,
CustomerAddress = customerAddrTxt.Text
};
listAccount.Add(account);
}
private void button6_Click(object sender, EventArgs e)
{
var sb = new StringBuilder();
foreach(var account in listAccount)
{
sb.AppendFormat("Customer ID: {0}\nCustomer Name: {1}\nCustomer Address: {2}\n\n", account.CustomerID, account.CustomerFullName, account.CustomerAddress);
}
viewDetailesTxt.Text = sb.ToString();
}
Been trying to solve this problem for hours now, and its frustrating me, hope anyone here can help me!
What im trying to do, is that i want the textbox to clear the text after i have searched for the word i have entered, and the richtextbox to delete whatever is in it when im searching for a new word.
private void button1_Click(object sender, EventArgs e)
{
string downloadedString;
System.Net.WebClient client;
string playerName = this.inputText.Text;
client = new System.Net.WebClient();
downloadedString = client.DownloadString("http:randomaddress;
string[] stringSeperator = new string[] { "\n" };
string[] result;
result = downloadedString.Split(stringSeperator, StringSplitOptions.None);
foreach (string s in result)
{
Bunch of if statements
}
public void SortString(string s)
{
//string manipulation
richTextBox1.Text += manipulate2 + "--" + " ";
}
public void SortString2(string s)
{
//string manipulation
richTextBox1.Text += manipulate2 + "--" + " ";
}
public void SortString3(string s)
{
//string manipulation
richTextBox1.Text += manipulate2 + "--" + " ";
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void True(object sender, PreviewKeyDownEventArgs e)
{
}
Been trying many different approaches but i just cant make it to work..
But to say again what it is what i want..
textbox is used for search, the input i get from the search gets showed in the richtextbox.
The search word should be cleared after i have entered the word and searched for it, and the richtextbox needs to clear the former search everytime i search again.
I suppose this is very simple, but havent worked with GUI for more than 2-3 days, used to console :)
Thank you in advance!
Oh and btw, everything else works like it should if that wasnt clear!
Ok...just Clear() them both after you have retrieved the search value?
string playerName = this.inputText.Text;
this.inputText.Clear();
richTextBox1.Clear();
// ... rest of your code ...