I have a problem with looping a list of songs. I have a List<String> _songList which contains songs paths (loaded correctly, checked). So I thought that there is an event which will tell me "Ok I stopped playing the song, I'm ready to play the next one". In NAudio it should be StoppedEventArgs added to WaveOutEvent.PlaybackStopped. But in my case it doesn't play another song, neither the same again. Here is my code:
public void Play_List(String _playlistName)
{
try
{
if (_songList.Count > 0)
{
if (!_paused)
{
_currentList = _playlistName;
PrimaryOutputStream =
new MediaFoundationReader(_songList[_songIndex]);
VolumeStream = new WaveChannel32(PrimaryOutputStream);
VolumeStream.PadWithZeroes = false;
Player.Init(VolumeStream);
Player.PlaybackStopped +=
new EventHandler<StoppedEventArgs>(RepeatMode);
}
Player.Play();
_paused = false;
_isPlaying = true;
}
}
catch (Exception e)
{
System.Windows.MessageBox.Show(e.ToString());
}
}
public void RepeatMode(object sender, StoppedEventArgs e)
{
try
{
if (_songList.Count > 0 && _currentSong != null)
{
_paused = false;
switch (_repeatMode)
{
case 1: //Repeat one song
Play_List(_currentList);
break;
case 2: //Repeat whole list
NextSong();
Play_List(_currentList);
MessageBox.Show("Changed song");
break;
default:
break;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Of course I set _repeatMode to 2 for list and 1 for one song.
I was searching the internet for help but found nothing. Anyone?
I do not see anything in your code which sets a value to the _currentSong. Probably, it is coming as null and your code is not getting executed.
if (_songList.Count > 0 && _currentSong != null)
Related
i want to compare the selecteditem of combobox with the selecteditem of other combobox
for this i have registered all the comboboxes in a list and named it "panel1kilist"
now the problem i am facing is that when there are same items in two comboboxes first the messagebox shows "no mattch found" and then it shows "match found" actually it goes to the else statement of inner loop first and then to if statement kindly help
private void button1_Click(object sender, EventArgs e)
{
bool check = false;
bool check1 = false;[![in this image you can see that there are two same items but message is showing "no match found"][1]][1]
try[![after clicking on ok button of message box showing "no match found" this message box shows up][1]][1]
{
for (int i = 1; i < panel1kilist.Count; i++)
{
for (int j = i + 1; j < panel1kilist.Count; j++)
{
if (panel1kilist[i].SelectedItem.ToString() == panel1kilist[j].SelectedItem.ToString())
{
if (check == false)
{
MessageBox.Show("match found");
}
check = true;
}
else
{
if (check1 == false)
{
MessageBox.Show("no match found");
}
check1 = true;
}
}
}
}
catch (System.NullReferenceException)
{
MessageBox.Show("please fill all the boxes first");
}
}
Your question is not really clear but I still try to give you some help. As mentioned in the comments there are several small issues in your code:
1. The outter for-loop
for (int i = 1; i < panel1kilist.Count; i++)
You define i = 1, which means you skip the very first item in your panel1kilist because lists and arrays start at index 0
2. Use of your bool variables
if (panel1kilist[i].SelectedItem.ToString() == panel1kilist[j].SelectedItem.ToString())
{
if (check == false)
{
MessageBox.Show("match found");
}
check = true;
}
else
{
if (check1 == false)
{
MessageBox.Show("no match found");
}
check1 = true;
}
You define your bool variables before starting your for-loops. So whenever you set your variables check and check1 to true, the if conditions check == false and check1 == false will never return true anymore. So you will never get any message except the very first "Match found" and "no match found".
3. My proposed solution
Make use of the foreach-loop and break the loops once you found a match, after the loops just show the message. Code:
var matchFound = false;
foreach (var combobox in panel1kilist)
{
foreach (var comboboxToMatch in panel1kilist.Skip(1))
{
if (combobox.SelectedItem.ToString() == comboboxToMatch.SelectedItem.ToString())
{
matchFound = true;
// Stops the inner loop in case of a match
break;
}
}
// Stops the outer loop in case of a match
if(matchFound)
{
break;
}
}
if(matchFound)
{
MessageBox.Show("match found");
}
I was just wondering what would be the best approach to refactoring this statement to use less of the condidtions? Im reallt strucggling to clean this statement up without having the same functionality if somone could point me in the right direction i would be very gratefull
try
{
var errorProviders = new List<ErrorProvider>() { epEmail, epAlternative, epMobile, epTown, epLandline, epHouseName, epForeName, epSurname, epPostcode, epCountry, epHouseName, epLocality, epCounty };
foreach (Control c in panel1.Controls)
{
if (c is SpellBox || c is TextBox)
{
if (!string.IsNullOrWhiteSpace(txt_ForeName.Text) | !string.IsNullOrWhiteSpace(txt_SurName.Text))
{
if (cmb_Title.SelectedIndex != -1)
{
if (cmb_PrefConTime.SelectedIndex != -1)
{
if (isPhoneNumber())
{
if (errorProviders.Any(e => e.GetError(c).Length > 0))
{
return false;
}
}
else
{
epPrefConNumber.SetError(cmb_PrefConNumber, "Error");
return false;
}
}
else
{
epPrefConTime.SetError(cmb_PrefConTime, "Error in: prefered contact time feild");
return false;
}
}
else
{
epTitle.SetError(cmb_Title, "Title");
return false;
}
}
else
{
epBothNames.SetError(txt_SurName, "Error:");
epBothNames.SetError(txt_ForeName, "Error:");
return false;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString())+ "Error has occurred, Please cancel and try again!");
}
return true;
If there is a way to use bare minumum conditions to reduce code ?
If you have to check all those conditions then you have to check all those conditions. Your most egregious issues, in my opinion, are the deep nesting and validating fields that are completely unrelated to the control inside your loop. You can fix the nesting by reversing your if conditions and returning early. For the rest, just move the unrelated validation outside the loop.
try
{
var errorProviders = new List<ErrorProvider>() { epEmail, epAlternative, epMobile, epTown, epLandline, epHouseName, epForeName, epSurname, epPostcode, epCountry, epHouseName, epLocality, epCounty };
if (string.IsNullOrWhiteSpace(txt_ForeName.Text) && string.IsNullOrWhiteSpace(txt_SurName.Text))
{
epBothNames.SetError(txt_SurName, "Error:");
epBothNames.SetError(txt_ForeName, "Error:");
return false;
}
if (cmb_Title.SelectedIndex == -1)
{
epTitle.SetError(cmb_Title, "Title");
return false;
}
if (cmb_PrefConTime.SelectedIndex == -1)
{
epPrefConTime.SetError(cmb_PrefConTime, "Error in: prefered contact time feild");
return false;
}
if (!isPhoneNumber())
{
epPrefConNumber.SetError(cmb_PrefConNumber, "Error");
return false;
}
foreach (Control c in panel1.Controls.Where(x => x is SpellBox || x is TextBox))
{
if (!errorProviders.Any(e => e.GetError(c).Length > 0))
{
return false;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString())+ "Error has occurred, Please cancel and try again!");
}
return true;
I have a weird behavior in my combobox. I have two combobox, one is cboSede an the other is cboGroup. CboSede enable cboGroup. I have already done this in other forms but here I get this message: ArgumentOutOfRangeException was unhandled by user code. The idea is if the user does not choose any value in cboSede then cboGroup is not enabled and in the other hand, if the user choose a valid option in cboSede, cboGroup is enable.
This is my code:
The SelectedIndexChanged of cboSede
private void cboSede_SelectedIndexChanged(object sender, EventArgs e)
{
if (Util.Security.ConexionBD)
{
if (Convert.ToInt32(cboSede.SelectedIndex) == 0 || Convert.ToInt32(cboSede.SelectedIndex) == -1)
{
cboGroup.Enabled = false;
cboGroup.SelectedIndex = 0;
}
else
{
this.FillGroupCombo();
cboGroup.Enabled = true;
}
}
else
MessageBox.Show("Error", "Warning",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
the FillGroupCombo function
private void FillGroupCombo()
{
try
{
Entity.Group objGroup = new Entidad.Group ();
objGroup .IdSede = Convert.ToInt32(cboSede.SelectedValue);
objGroup = Control.Group.ListBySede(objGroup );
if (objGroup != null && objGroup.ListGroup.Count > 0)
{
Entity.Group objMsje = new Entity.Group();
objMsje.IdGroup = -1;
objMsje.Name= "--- Select group ---";
objGroup.ListGroup.Insert(0, objMsje);
}
else
{
Entity.Group objMsje = new Entity.Group();
objMsje.IdGroup = 0;
objMsje.Name= "-- No groups found --";
objGroup.ListGroup.Insert(0, objMsje);
}
Util.Utilitario.FillCombo(objGroup.ListGroup, this.cboGroup, "IdGrupo", "Name");
}
catch (Exception ex)
{
Util.Security.Insert(ex);
Util.Security.SaveLog(ex.Message);
}
}
Any idea about why this happens?
This one
if (Convert.ToInt32(cboSede.SelectedIndex) == 0 || Convert.ToInt32(cboSede.SelectedIndex) == -1)
{
cboGroup.Enabled = false;
cboGroup.SelectedIndex = 0;
}
Will kill the code when SelectedIndex == -1 and you actually have no item in your comboBox (when index = 0, it is OutOfRange)
you can give an if condition if you want
if (cboGroup.Items.Count > 0)
cboGroup.SelectedIndex = 0;
This way, it first check of the comboBox really have anything. And if it doesn't then it won't produce OutOfRange error
Im making a chat program that saves the messages in files like pub0.zzc, all computers that are using it will be connected to the hard drive that these files are in, so its fine. The method data.Chat.Read(MessageTypes type, string Channel) infinite loops through a try catch statement till it returns the messages. I used this before and works perfectly. But, my code was hard to manage so instead of just putting text boxes into the window and using the code each time, i created a user control (MessageViewer). It works fine, once again when I run it, BUT it freezes VS whenever I try to use the designer on the window housing the control. the probelm isnt the window because when i delete the control its fine. I think the possible errors are at RefreshMessages() and the Refresher_Tick(...)
Refresher.Stop() and .Start() is also not it, worked fine before
so here is the code:
private void Refresher_Tick(object sender, EventArgs e)
{
Refresher.Stop();
int RefreshRate = 4;
bool Live = true;
if (RefreshRateChoice == "Manual")
{
Live = false;
RefreshRate = 1;
}
else if (RefreshRateChoice == "4 ( Default )")
{
Live = true;
RefreshRate = 4;
}
else
{
Live = true;
RefreshRate = Convert.ToInt32(RefreshRateChoice);
}
if (data.Chat.Read(MessageType, ChannelChoice) != ContentPresenter.Text && Live)
{
RefreshMessages();
}
Refresher.Interval = RefreshRate;
Refresher.Start();
}
public void RefreshMessages() {
if (data.Chat.Read(MessageType, ChannelChoice) != ContentPresenter.Text)
{
ContentPresenter.Text = data.Chat.Read(MessageType, ChannelChoice);
}
}
and if you need it:
public static string Read(MessageTypes Type, string Channel)
{
string Loc;
if (Type == MessageTypes.Public && (Channel == "1" || Channel == "2"))
{
return "Can not view this channel, only post to it.";
}
if (Type == MessageTypes.Public)
{
Loc = data.AssetsFolder + "\\pub" + Channel + ".zzc";
}
else if (Type == MessageTypes.Private)
{
Loc = data.AssetsFolder + "\\" + Channel + ".zzpc";
}
else if (Type == MessageTypes.Game)
{
Loc = data.AssetsFolder;
}
else
{
Loc = data.AssetsFolder;
}
while (true)
{
try
{
String MessageList = "";
StreamReader MessageReader = new StreamReader(Loc);
string EncMessages = MessageReader.ReadToEnd();
MessageReader.Dispose();
List<string> EncMsgList = EncMessages.Split(';').ToList();
for (int i = 1; i < EncMsgList.Count; i++)
{
MessageList += data.Encodings.Decrypt(EncMsgList[i], Palettes.Message) + "\n";
}
return MessageList;
}
catch
{
// Do nothing
}
}
}
You say that it "freezes."
In your Read method you have a while(true) loop with an embedded try...catch block, but the catch never returns you from that method. If you keep throwing the same exception, you'll continue to loop over and over which could be where you are freezing.
At least to prove that is the case, put a return in you catch or some diagnostic code to indicate if that is the case.
if (t != null) is always null why help..
when ever i try to get value in the variable name t it always gets in the else part but i am sure that there is valuse in tat variable.
private void button3_Click(object sender, EventArgs e)
{
try
{
if (search=="")
{
}
else
{
if (textBox1.Text=="")
{
MessageBox.Show("Select A Task Or Find One");
}
else
{
search = textBox1.Text;
}
}
if (search != null)
{
t = tasks.OpenTask(search);
if (textBox2.Text!="")
{
short hour = short.Parse(textBox2.Text.Substring(0, 2));
short minute = short.Parse(textBox2.Text.Substring(3, 2));
if (t != null) // this is null dont know why
{
foreach (Trigger tr in t.Triggers)
{
if (tr is StartableTrigger)
{
(tr as StartableTrigger).StartHour = hour;
(tr as StartableTrigger).StartMinute = minute;
}
}
t.Save();
t.Close();
}
tasks.Dispose();
button2.Visible = true;
textBox3.Visible = true;
search = "";
}
else
{
MessageBox.Show("Enter Time ");
}
}
}
catch (Exception b)
{
MessageBox.Show(b.ToString());
// MessageBox.Show("Select A Task From The List ");
}
}
help guys .. well i tried it to debug but didnt get a break through..
t is null because tasks.OpenTask(search) returns null.
Probably there is no task matching your search criteria.
Why are you disposing of tasks in the first place?
Any place in your source ,where you have written something like this MyClass t = new MyClass().. where t is your class object. If you have not declared,It will always come null.
Or might be you have declared something like this
private Task t; but forgot to add new keyword. Checkout!!!