I have a combobox called combobox1 and I dont know how to save the selection. For example if i selected Sub Compounds, how would i save this so when i loaded it again from the hd Sub Compounds would be selected.

Dani AI

Generated

's file-based example is a clear, minimal way to persist a ComboBox selection between runs. It works well for quick tests and single-user tools, but a few practical considerations make the approach more robust in real applications.

Prefer storing persisted data in a per-user application-data folder instead of a hard-coded root path and build paths with Path.Combine. Decide what to persist: SelectedIndex is simple but fragile if the item list changes; persisting a stable item ID or value survives reordering or label edits. Restoration must happen after the ComboBox is populated — for data-bound or asynchronous loads, perform the restore in the data-load completion event. When matching by text, trim the saved value and use exact matching, then verify the item exists before assigning the selection; fall back to a safe default when the saved value is missing.

Wrap file IO with exception handling and ensure streams are disposed (for example via using) to avoid locked files. Common failure modes to check are wrong path/permissions, encoding mismatches for non-ASCII entries, and attempting to restore before items exist. For WinForms apps, a user-scoped Properties.Settings entry is a simpler alternative to manual files. For ASP.NET scenarios, session state, cookies, user profile, or a database are more appropriate depending on persistence needs. Given 's sample worked for , sensible next steps are removing hard-coded paths, adding basic error handling, and choosing whether to persist an index, text, or stable ID.

Recommended Answers

All 2 Replies

Hi!

I made this sample, which saves the combobox item when application terminates and load and select the combobox last saved item when application starts:

private void Form1_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
{
	System.IO.StreamWriter wr = new System.IO.StreamWriter("C:\\abc.txt");
	wr.WriteLine(ComboBox1.Text);
	wr.Close();
}

private void Form1_Load(System.Object sender, System.EventArgs e)
{
	if ((System.IO.File.Exists("C:\\abc.txt") && new System.IO.FileInfo("C:\\abc.txt").Length > 0)) {
		System.IO.StreamReader sr = new System.IO.StreamReader("C:\\abc.txt");
		string item = sr.ReadLine();
		int index = ComboBox1.FindString(item);
		if ((index != -1 & !string.IsNullOrEmpty(item))) {
			ComboBox1.SelectedIndex = index;
		}
		sr.Close();
	}
}

Is this helpful ??

yes thank you very much! i appreciate it

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.