What's a good way to "run all checked items in a checked listbox"?

  • Thread starter sherifffruitfly
  • Start date
S

sherifffruitfly

Hi,

I've got a checked list box, and a "go' button on the form. Each item
in the checked list box is associated with a program (say notepad,
calc, etc.). When the user clicks "go", every item that is checked is
to be run.

I'm looking for an elegant and extensible way to do this. I'm currently
using an if block, which just seems silly to me. Structurally, it's the
equivalent of the below. Any ideas on alternatives would be much
appreciated. What I have looks asinine.

In particular, it would be nice to be able to "run all checked",
without having to specify at compile time just what the possibilities
are (ie, the user might be able to add items to the list).

thanks,

cdj

==========================
private void btn_Gather_Click(object sender, System.EventArgs e)
{
if (chkListBox_AvailProgs.CheckedItems.Count == 0)
{
MessageBox.Show("There are no programs checked.", "Program selector
Error");
}
else if (dateTimePickerStart.Value.DayOfWeek.ToString() == "Sunday"
|| dateTimePickerStart.Value.DayOfWeek.ToString() == "Saturday")
{
MessageBox.Show("Date must be Monday-Friday.", "Program selector
Error");
}
else
{
if (chkListBox_AvailProgs.CheckedItems.Contains("Notepad"))
{
RunNotepad();
}

if (chkListBox_AvailProgs.CheckedItems.Contains("Calc"))
{
RunCalc();
}

if (chkListBox_AvailProgs.CheckedItems.Contains("Paint"))
{
RunPaint();
}
}
}
 
D

Dave Sexton

Hi,

Define your own list item:

internal class ProgramListItem
{
public string Title { get { return title; } }

public string Path { get { return path; } }

private readonly string title, path;

public ProgramListItem(string title, string path)
{
this.title = title;
this.path = path;
}

/// <summary>
/// Provides the display text to the CheckedListBox control
///</summary>
public override string ToString()
{
return title;
}
}


When you populate the list, do so by constructing instances of the
ProgramListItem class:

chkListBox_AvailProgs.Items.Add(new ProgramListItem("Calculator",
@"calc.exe"));
chkListBox_AvailProgs.Items.Add(new ProgramListItem("Notepad",
@"notepad.exe"));


You can then run the checked programs as follows:

private void btn_Gather_Click(object sender, EventArgs e)
{
// iterate over each checked item
foreach (ProgramListItem item in checkedListBox1.CheckedItems)
{
RunProgram(item.Path);
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top