I want to reload the combo box so that it would display the values recently entered by me.
The Language used is C#.Net 2005..I am making a windows application. Please guide me?
you just need to call the method .DataBind() every time you want to "refresh" the combobox with new data
Save your last entered values, then load them when the comboBox is loaded. Something like:
private stirng _comboBoxSavedListPath = "";//or from application settings..
private List<string> _comboBoxLastEnteredValues = new List<string>();
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)//or whenever you want to save
{
if (comboBox1.SelectedIndex > -1)
{
string entry = comboBox1.SelectedItem.ToString();
if (!_comboBoxLastEnteredValues.Contains(entry))
{
_comboBoxLastEnteredValues.Add(entry);
}
}
}
Now handle the form Closing event or just save the list again whenever item added. and load the list whenever form is loaded:
private void form1_Closing..
{
SaveList(_comboBoxLastEnteredValues);//Like(File.WriteAllLines(_comboBoxLastEnteredValues.ToArray(), _comboBoxSavedListPath);
}
private void form1_Load...
{
_comboBoxLastEnteredValues = LoadLastSavedList();//Like File.ReadAllLines(_comboBoxSavedListPath);
}
Related
I'm working on a GUI for an admin interface for management of a student complex. Currently the GUI has a listbox with predefined 6 rules for the students. In the beginning of the code, I add them to a list
private void Form1_Load(object sender, EventArgs e)
{
foreach (string rule in lbRules.Items)
ruleList.Add(rule);
}
Then, the GUI provides the admin with an option to modify the rules. To do so he selects a rule from the listbox and clicks a "Modify" button, which opens another form:
private void BtnModify_Click(object sender, EventArgs e)
{
if (lbRules.SelectedItems.Count > 0)
{
selectedRule = lbRules.SelectedItem.ToString();
selectedIndex = lbRules.SelectedIndex;
selectedRuleNumber = selectedRule.Substring(0, 3);
selectedRule = selectedRule.Substring(6);
var rulesForm = new Rules();
rulesForm.Show();
}
}
On the second form load event I get the rule's text and number:
private void Rules_Load(object sender, EventArgs e)
{
tbRule.Text = Form1.selectedRuleNumber;
tbModifyRule.Text = Form1.selectedRule;
}
The text gets added to a RichTextBox, from where the rule can be edited.
Then the admin clicks a "Save" button, which gets the edited text from the RichTextBox(tbModifyRule) and adds it to a static ruleList in form1, sets a static boolean from form1 to true. Afterwards the second form gets closed:
private void BtnSave_Click(object sender, EventArgs e)
{
saveRule = Form1.selectedRuleNumber + " - " + tbModifyRule.Text;
Form1.ruleList.Insert(Form1.selectedIndex, saveRule);
Form1.ruleList.RemoveAt(Form1.selectedIndex+1);
Form1.formOpen = true;
this.Dispose();
}
At this point we are back to form1, in which we have a timer with timer_tick event. In there we check whether the boolean formOpen is true (which it is set before closing form2). Inside the if statement we clear the listbox and add each rule from the ruleList (previously edited in form2) to the listbox, then sets the formOpen back to false so it doesn't get executed all the time:
if (formOpen)
{
lbRules.Items.Clear();
foreach (string item in ruleList)
lbRules.Items.Add(item);
}
formOpen = false;
Now this is really weird, and at this point makes absolutely no sense to me, since I tried debugging it for over an hour, trying different ways, which also led me to mysterious wonders of WHY TF IT WORKS WHENEVER IT WANTS...
So this works randomly, like it would work the first time, the second and third times it won't. Or vice versa. It's all random.
Strangely, I tried adding a breakpoint on the
lbRules.Items.Add(item);
in the foreach loop, so it stops on each item. And I actually saw the changed rule getting added from the ruleList into the listBox, however in the end it was not there.
And weirdly enough, I also tried adding the text from form2 in the listBox in form1, without using a list, but for whatever odd reason, I use the int selectedIndex, which gets the index of the selected item from the BtnModify_Click event to insert the text in that particular index, but this very index gets RANDOMLY set to bloody 0 after form2 closes.
hence, it again works from time to time, because at some tries it doesn't get set to 0 and it works.
if (formOpen)
{
selectedRule = Rules.saveRule;
lbRules.Items.Insert(selectedIndex, selectedRule);
lbRules.Items.RemoveAt(selectedIndex+1);
}
formOpen = false;
I don't assign value to this integer ANYWHERE else in the code.
I really tried digging some sense, but I hit a solid hard rock.
Any help appreciated!
And thanks for the time!
edit1:
as requested - rest of the timer method
private void Timer1_Tick(object sender, EventArgs e)
{
foreach (string text in ws.messages)
message = text;
if (ws.messages.Count > 0)
{
if (message.Contains("comp"))
{
Complaints();
message = String.Empty;
ws.messages.Clear();
}
}
if (formOpen)
{
lbRules.Items.Clear();
foreach (string item in ruleList)
lbRules.Items.Add(item);
}
formOpen = false;
}
I would change your code to the following:
if (formOpen)
{
formOpen = false;
lbRules.Items.Clear();
foreach (string item in ruleList)
lbRules.Items.Add(item);
}
The issue with having the formOpen = false; outside the if statement is that there is a chance that once the user clicks the Save button the timer could be about to execute the formOpen = false instruction setting it to false making the code inside the If statement to never be executed.
I truly believe this is not random but just a timing issue due to complicated logic.
If I were you, I'd do a couple things:
Use a separate class for data exchange between forms, avoid using public static (I assume) form members for this.
Instead of a timer, subscribe to the Form.Closed event of RulesForm
This might make code flow a bit more predictable and allow you to find errors more easily.
Better yet, use the following pattern:
class Form1
{
private void BtnModify_Click(object sender, EventArgs e)
{
var ruleData = ..... //get current rule data
var rulesForm = new Rules();
rulesForm.SetData(ruleData); //pass initial state to the form
rulesForm.SaveChanges = this.ApplyRules; //pass a method which will be called on save
rulesForm.Show();
}
private bool ApplyRules(RuleData ruleData)
{
//do whatever you like with the rules here
return true;
}
}
class RuleForm
{
public void SetData(RuleData ruleData)
{
//initialize fields, etc
}
public Func<RuleData, bool> SaveChanges { get; set; }
private void BtnSave_Click(object sender, EventArgs e)
{
var ruleData = .... //get data from form fields
if(this.SaveChanges(ruleData))
this.Close();
}
}
class RuleData
{
//whatever data you need
}
Long story short: There are specific tags given (like Pop, Rock, Metal) and the User should write into a textbox and every time he adds a char the given tags are checked if one (or more) matches. At the moment I'm using a combobox with the following code:
private void EnterComboBox_TextChanged(object sender, EventArgs e)
{
List<string> AllTags = new List<string>();
AllTags.Add("Pop");
if (AlleTags[0].ToLower().StartsWith(EnterComboBox.Text.ToLower()))
{
EnterComboBox.Items.Clear();
EnterComboBox.Items.Add("Pop");
EnterComboBox.DroppedDown = true;
}
}
this is working fine but the problem is, that after the first char entered the dropbox drops down and the entered text is marked and will be overwritten when a new char is entered. Any ideas how I could fix this? Every idea is welcome it doesn't have to be a combo box :)!
Edit:
After some more (detailed) research I realized I could explain it like this: Basically I want the combobox the behave like the search-bar from google. The users enters letters and in the dropdown menu are autocomplete suggestions
At the moment I solved it like this:
I placed a textbox in front of a combobox so that only the arrow of the combobx is visible and if you click on it you automatically write in the textbox.
public Form1()
{
InitializeComponent();
EingabeTextBox.AutoSize = false;
EingabeTextBox.Size = new Size(243, 21); //the size of the combobox is 260;21
}
private void EingabeTextBox_TextChanged(object sender, EventArgs e)
{
EingabeComboBox.Items.Clear();
List<string> AlleTags = new List<string>();
AlleTags.Add("Example");
if (AlleTags[0].ToLower().StartsWith(EingabeTextBox.Text.ToLower()))
{
EingabeComboBox.Items.Add(AlleTags[0]);
EingabeComboBox.DroppedDown = true;
}
}
For me it would work like this. I hope I can help someone else with this too, but I am still open for any better ideas :)!
Changing the ComboBox entries while typing into it obviously creates undesired interferences. Instead combine a TextBox and a ListBox.
private bool changing;
private void TextBox_TextChanged(object sender, EventArgs e)
{
if (!changing) {
changing = true;
try {
// manipulate entries in the ListBox
} finally {
changing = false;
}
}
}
private void ListBox_IndexChanged(object sender, EventArgs e)
{
if (!changing) {
changing = true;
try {
// Put selected entry into TextBox
} finally {
changing = false;
}
}
}
The changing guard makes sure that the ListBox does not influence the TextBox while you are entering text into the TextBox and vice versa.
The try-finally ensures that the guard will be reset in any circumstances, even if an exception should occur.
I have a question about saving content from a listbox and putting it in a .ini file. Also i want to retrieve the information and put it back in the listbox when the programm starts.
I have two listboxes lets call them listBox1 and listBox2.
And 1 button lets call that selectbttn.
The content from listBox2 must be saved when i click on the select button. ,br />
How can i fix this?
This is the code with the 2 listboxes, id ont have a code for the select button.
The button that you see in the code is a add button that adds content from listbox1 to listbox 2.
private void add_button_Click(object sender, EventArgs e)
{
try
{
if (list_selected.Items.Contains(List_selection.SelectedItem))
{
MessageBox.Show("Can not add the type twice.");
}
else
{
list_selected.Items.Add(List_selection.SelectedItem);
}
}
catch
{
{
MessageBox.Show("No type selected");
}
}
}
You need to use a StreamWriter to save to the file. You could do something like the following:
public void SaveFile_Click(object sender, EventArgs e)
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\YourFile.ini"))
{
foreach (var item in list_selected.Items)
{
file.WriteLine(item.ToString());
}
}
}
http://msdn.microsoft.com/en-us/library/vstudio/8bh11f1k.aspx
You can use a StreamReader to read back the contents of the .ini file when your application loads. I will leave this to you since you did not originally provide code.
Write
File.WriteAllLines("test.ini",
listbox.Items.Cast<ListItem>().Select(i => i.Text).ToArray());
Load
listbox.Items.AddRange(File.ReadAllLines("test.ini")
.Select(l => new ListItem(l)).ToArray());
I have an issue with a ComboBox
private void Form_AddGoal_Load(object sender, EventArgs e)
{
LoadGoal();
IList<Perspective> perspectives = PerspectiveRepository.All(); // I get all perspectives
CBPerspective.DataSource = perspectives;
CBPerspective.DisplayMember = "Name";
// Here I initialize other components
}
private void LoadGoal()
{
if (Goal== null)
Goal = new Goal();
// Here I bind other components
CBPerspective.DataBindings.Add("SelectedItem", Goal, "Perspective");
}
public void SaveBtn_Click(object sender, EventArgs e)
{
// I save the Goal
}
When the form is open, all is ok. If I don't choose any option in the combobox (That is, the first option keep it) and I save the data on the form the Perspective property is null but If I choose other option in the combobox and proceed in the same way, perspective is equal to the selected item so works perfectly.
What is going on? Do I need trigger an event?
This is the code:
private void button1_Click(object sender, EventArgs e)
{
List<string> user = new List<string>();
user.Add(usertextBox.Text);
I want it where each time I press the button, whatever is in usertextBox at that point gets added to the list 'user' as a new item, so I can recall the different ones later with [1], [2], [3], etc. I also want it so the user can close the app and all the users will still be saved. I I don't know if C# does this automatically
Even if you can only answer one of my questions that's fine. Thanks!!
In your code you are making List local to Button that means every time you click button new object of List is created, You should create it out side button click method. Try this.
List<string> user = new List<string>();
private void button1_Click(object sender, EventArgs e)
{
user.Add(usertextBox.Text);
You have to define the List out side of the method. C# does not keep the content of the list.
private List<string> user = new List<string>();
private void button1_Click(object sender, EventArgs e)
{
user.Add(usertextBox.Text);
}
for saving the content you could use a database (http://msdn.microsoft.com/en-us/library/bb655884%28v=vs.90%29.aspx) or an xml file (http://www.codeproject.com/Articles/7718/Using-XML-in-C-in-the-simplest-way).
to save the content of the List you could create a new class containing this two methods instead of the list
public List<string> getListContent()
{
//read xml-file
}
public void Add(string t)
{
//write to xml file
}
This will just fine work in single thread applications.