CheckBox for Windows Phone - c#

I used 4 checkbox in my application and created an integer list to add value if the checkbox is checked. The value will be stored in my database using sqlite. This is my code :
List<int> hobid = new List<int>();
private void Button_Click_1(object sender, RoutedEventArgs e)
{
if (Convert.ToBoolean(cricket.IsChecked))
{
hobid.Add(1);
}
else if (Convert.ToBoolean(football.IsChecked))
{
hobid.Add(2);
}
else if (Convert.ToBoolean(music.IsChecked))
{
hobid.Add(3);
}
else if (Convert.ToBoolean(reading.IsChecked))
{
hobid.Add(4);
}
int rec;
string strInserthob = "Insert into User_hobbies (User_id,Hobbies_id) values (#User_id,#Hobbies_id)";
//Here insertion is done..
for (int i = 0; i < hobid.Count; i++)
{
User_hobbies txt = new User_hobbies
{
User_id = userid,
Hobbies_id = hobid[i]
};
rec = (Application.Current as App).db.Insert<User_hobbies>(txt, strInserthob);
}
}
Can you suggest me how to get the value in a list whatever checkbox is checked.

I'm assuming the button click is a 'Save' action.
In that case, you're only saving the first match due to the else if statements. The real quick and nasty way to do it is just remove the 'if else' statements and replace it with a straight if.
if (Convert.ToBoolean(cricket.IsChecked))
{
hobid.Add(1);
}
if (Convert.ToBoolean(football.IsChecked))
{
hobid.Add(2);
}
if (Convert.ToBoolean(music.IsChecked))
{
hobid.Add(3);
}
if (Convert.ToBoolean(reading.IsChecked))
{
hobid.Add(4);
}

Related

Injection of radiobuttonlist selected value into class

I want to create a webform with 4 types of phones like: LG, xiaomi, samsung and iphone. They will be in an Array and I will insert them into dynamic radiobuttonList in the page init.
Also, the user will have a textbox where he will put an amount of money he has. The user will also have a button that will calc if he have the budget for the selected phone from the list.
After the user selects the phone, write in the budget and press the button
he will get "in budget" or "not enough budget".
The class have property of the array to insert the all the array from the page init and will have 2 functions:
One function will take the budget number > will go to the 2nd function that will see the selected phone and the budget > do its calcs and return the result into the 1st func that will give the feedback.
Now where I am stuck:
if the class isnt made global - and i put it in init or in button click - it wont work, so im looking for a way to make it work but without putting it global
so far i managed to inject the selected value into a class property and than compare - but i want to know if there is a way that this can happen with array inside class property
maybe if anyone can help me out and refer me to a guide where i can learn more about this subject (how inject selected value into function of a class and etc) ill be glad! as everything i see is C# with console but i work with ASP.NET WEB APPLICATION (.netframework)
enter code here
namespace gfjsr{
public partial class WebForm1 : System.Web.UI.Page{
phone InsertUserInfo = new phone();
protected void Page_init(object sender, EventArgs e){
string[] myArr = new string[] { "samsung", "IPHONE", "XIAOMI","LG"};
RadioButtonList phoneList = new RadioButtonList();
phoneList.ID = "radioList";
for (int i = 0; i< myArr.Length; i++)
{
ListItem li = new ListItem();
li.Text = myArr[i];
li.Value = i.ToString();
phoneList.Items.Add(li);
}
Panel1.Controls.Add(phoneList);
Label budgetLb = new Label();
budgetLb.ID = "budglb";
budgetLb.Text = "write your budget";
Panel1.Controls.Add(budgetLb);
TextBox insertBudg = new TextBox();
insertBudg.ID = "budgTxt";
Panel1.Controls.Add(insertBudg);
Button myBtn = new Button();
myBtn.ID = "btn1";
myBtn.Click += new EventHandler(btn1_click);
myBtn.Text = "result";
Panel1.Controls.Add(myBtn);
Label Labelfeedback = new Label();
Labelfeedback.ID = "feedback";
Labelfeedback.Text = "";
Panel1.Controls.Add(Labelfeedback);
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn1_click(object sender, EventArgs e)
{
InsertUserInfo.phoneChosen = ((RadioButtonList)FindControl("radioList")).SelectedItem.Text;
double UserBudget =
Convert.ToDouble(((TextBox)FindControl("budgTxt")).Text);
InsertUserInfo.BudgetYN(UserBudget);
((Label)FindControl("feedback")).Text = InsertUserInfo.feedback; }}}
namespace gfjsr{
public class phone{
private string _phoneChosen;
public string phoneChosen
{
get { return _phoneChosen; }
set { _phoneChosen = value; }
}
private string _feedback;
public string feedback
{
get { return _feedback; }
set { _feedback = value; }
}
public double Func1(string x)
{
double phonePrice = 0;
if( x == "samsung")
{
phonePrice = 4000;
}
if (x == "IPHONE")
{
phonePrice = 3500;
}
if (x == "XIAOMI")
{
phonePrice = 3000;
}
if (x == "LG")
{
phonePrice = 2000;
}
return phonePrice;
}
public void BudgetYN(double y)
{
if(y >= Func1(_phoneChosen))
{
_feedback = "positive";
}
else
{
_feedback = "no";
}
}
}
}

WPF Button click not properly comparing variable to array value

new to WPF so not sure if there is some sort of syntax that I am missing or what.
Course choice;
int totalCredits = 0;
int classesRegistered = 0;
string[] registeredCourses = new string[3];
private void button_Click(object sender, RoutedEventArgs e)
{
if (classesRegistered < 3)
{
choice = (Course)(this.comboBox.SelectedItem);
if ((!choice.Equals(registeredCourses[0]))
&& (!choice.Equals(registeredCourses[1]))
&& (!choice.Equals(registeredCourses[2])))
{
registeredCourses[classesRegistered] = choice.ToString();
this.listBox.Items.Add(registeredCourses[classesRegistered]);
classesRegistered = classesRegistered + 1;
}
}
}
So I don't want the choice to be added to the listbox if its already registered to one of the array's values. What is it I'm missing?
Your if statement is comparing a string to a Course object, you may change it to below:
if(!registeredCourses.Any(obj=> obj.Equals(choice.ToString())))

Remove CheckListBox CheckedItems

I have a timer event that does several things. One item I am trying to get it to do is to programmatically remove the CheckListBox items that are checked once the timer hits the completed action I am performing.
This is the code for the timer and what I have tried to do.
private void timer1_Tick(object sender, EventArgs e)
{
string s;
if (DbFirmwareUpdateComplete.WaitOne(1))
{
DbFirmwareUpdateComplete.Reset();
mnuLoadKeyFile.Enabled = true;
}
if (DbUpdateComplete.WaitOne(1))
{
DbUpdateComplete.Reset();
mnuLoadKeyFile.Enabled = true;
btnLoad.Enabled = true;
}
if (CacheComplete.WaitOne(1))
{
CacheComplete.Reset();
btnLoad.Enabled = true;
}
if (UpdateRunning)
{
bool UpdateDone = true;
int StillActive = 0;
// loop through all active jobs to check if all have completed
foreach (clsCnaPair cna in ActiveJobs)
{
if (cna.Job.JobComplete == false)
{
UpdateDone = false;
StillActive++;
}
else
{
if (cna.Job.UpdateSuccess)
{
// Update color of CLB.Items.Selected if success.
int count = CLB.Items.Count;
for (int index = count; index > 0; index--)
{
if(CLB.CheckedItems.Contains(CLB.Items[index-1]))
{
CLB.Items.RemoveAt(index - 1);
}
}
}
else
{
// Update color of CLB.Items.Selected if failed.
}
}
}
if (UpdateDone)
{
UpdateRunning = false;
log("All Update jobs have finished.");
}
if (ckTop.Checked == true)
{
ckTop.Checked = false;
}
else
{
ckTop.Checked = false;
}
When I run the program and it hits this piece;
if (cna.Job.UpdateSuccess)
{
// Update color of CLB.Items.Selected if success.
int count = CLB.Items.Count;
for (int index = count; index > 0; index--)
{
if(CLB.CheckedItems.Contains(CLB.Items[index-1]))
{
CLB.Items.RemoveAt(index - 1);
}
}
}
I get an error:
System.ArgumentOutOfRangeException: InvalidArgument=Value of '-1' is not valid for 'index'.
Parameter name: index
The Error occurs after this piece of code;
private void CLB_SelectedIndexChanged(object sender, EventArgs e)
{
// One of the CNA IPs was selected. sender is the CheckedListBox.
// Here we want to display its fingerprint in the text box, or if the push is running, the status.
// get the CnaPair class represented by this IP:
clsCnaPair CnaPair = (clsCnaPair)CLB.Items[CLB.SelectedIndex];
// Display the corresponding fingerprint string in the editBox:
if (CnaPair.Job != null) txtStatus.Text = CnaPair.Job.GetStatus();
else txtStatus.Text = CnaPair.GetInfo();
}
Or more specifically at the line:
clsCnaPair CnaPar = (clsCnaPair)CLB.Items[CLB.SelectedIndex];
What am I missing? Searching google, shows the way I am doing the remove is consistent with the examples found there.
Thanks,
It's dangerous to modify the contents of the ChecklistBox inside a loop when the loop conditions depend on the contents of the ChecklistBox. Once you call RemoveAt(), the CheckedItems list and the CLB.Items.Count has changed and you will have a problem. In this case, the loop fired the SelectedIndexChanged() event with an invalid Index (-1).
Better to do this in a do-while loop:
bool done;
do
{
done = true;
for (int index = CLB.Items.Count; index > 0; index--)
{
if(CLB.CheckedItems.Contains(CLB.Items[index-1]))
{
CLB.Items.RemoveAt(index - 1);
done = false;
break;
}
}
}while(!done);
This way, every time an item is removed, you break out and start the loop all over again.
After some experimentation, I commented out the CLB_SelecteIndexChanged code and it now completes with the original code.
That leaves one issue. What is the work around with the CLB_SelectedIndexChanged code left in. I will work on that one more and see f I can figure it out with what you guys have provided.
Thanks to both m.rogalski and mcNets.

List<> not working properly

there is a listView,label which shows the current count of a list called Name, and there is a event that raise when list count goes beyond 5. but when ever i enter the names in textbox (it goes to the list) it shows the count but the list view is not getting them properly.EX- when i enter the first name label shows the count as 1 and list view shows the name i entered in textbox and WHEN I ENTERED THE SECOND NAME label shows the list counter correctly but list view adds not only the second item i entered but also the first i have enetered before. then there is three items in list view. here is my code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List<string> emps = new List<string>();
private void button1_Click(object sender, EventArgs e)
{
listMake lm = new listMake();
lm.ListItemAdded += new listMake.listMethods(lm_ListItemAdded);
lm.adding(emps, textBox1,listView1);
label1.Text = emps.Count.ToString();
}
void lm_ListItemAdded(List<string> names)
{
MessageBox.Show("it enough i think its more than 5");
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
class listMake
{
public delegate void listMethods(List<string> names);
public event listMethods ListItemAdded;
public List<string> Name = new List<string>();
public void adding(List<string>Name,TextBox t1,ListView l1)
{
try
{
if (t1.Text != "")
{
Name.Add(t1.Text);
for (int i = 0; i < Name.Count; i++)
{
l1.Items.Add(Name[i]);
}
if (Name.Count > 5)
ListItemAdded(Name);
}
}
catch (Exception er) { MessageBox.Show(er.StackTrace); ;}
}
}
Problem : You are not clearinig the ListView Items each time you add items from the list.
Solution 1 : you need to clear the items from listview before adding into it.
if (t1.Text != "")
{
Name.Add(t1.Text);
l1.Items.Clear(); //add this statement
for (int i = 0; i < Name.Count; i++)
{
l1.Items.Add(Name[i]);
}
if (Name.Count > 5)
ListItemAdded(Name);
}
Solution 2: You can add only the item enetered in TextBbox instead of adding all items from begining.so you needto remove the for-loop here.
if (t1.Text != "")
{
Name.Add(t1.Text);
l1.Items.Add(t1.Text);
if (Name.Count > 5)
ListItemAdded(Name);
}

c# - ArgumentOutOfRangeException: Index was out of range - 2 Forms

Problem solved.
The original "private void buttonSave_Click" was changed to:
private void buttonSave_Click(object sender, EventArgs e)
{
if (MusicCollection.FormMain.PublicVars.AlbumList.Count != 100)
{
MusicCollection.FormMain.PublicVars.AlbumList.Add(new Album(NameTextBox.Text));
MessageBox.Show("New Album added: " + NameTextBox.Text);
formMain.ListAlbums(formMain.AlbumsListBox.Items);
this.Close();
}
else
{
MessageBox.Show("No room for new album.");
this.Close();
}
}
Original Post:
I'm new to using C#, so appologies for any seemly obvious mistakes or terrible coding.
I'm trying to create a new Album object (that gets its Name from NameTextBox.Text on Form FormAlbumAC) and add it to List AlbumList when the user clicks the save button on FormAlbumAC. Then I want to list all of AlbumList in a ListBox on Form FormMain.
When I run the program and click the save button, I'm getting the error "ArgumentOutOfRangeException was unhandled, Index was out of range" at the line:
if (MusicCollection.FormMain.PublicVars.AlbumList[i] == null)
// line 8 on my excerpt from Form FormAblumAC
I'm not sure what I'm doing wrong. Any help would be much appreciated, thank you.
Form FormMain:
public const int MAX_ALBUMS = 100;
public int totalAlbums = 0;
public FormMain()
{
InitializeComponent();
}
public static class PublicVars
{
public static List<Album> AlbumList { get; set; }
static PublicVars()
{
AlbumList = new List<Album>(MAX_ALBUMS);
}
}
public ListBox AlbumListBox
{
get
{
return AlbumListBox;
}
}
public void ListAlbums(IList list)
{
list.Clear();
foreach (var album in PublicVars.AlbumList)
{
if (album == null)
continue;
list.Add(album.Name);
}
}
Form FormAlbumAC:
private FormMain formMain;
private void buttonSave_Click(object sender, EventArgs e)
{
int index = -1;
for (int i = 0; i < MusicCollection.FormMain.MAX_ALBUMS; ++i)
{
if (MusicCollection.FormMain.PublicVars.AlbumList[i] == null)
{
index = i;
break;
}
}
if (index != -1)
{
MusicCollection.FormMain.PublicVars.AlbumList[index] = new Album(NameTextBox.Text);
++formMain.totalAlbums;
MessageBox.Show("New Album added: " + NameTextBox.Text);
formMain.ListAlbums(formMain.AlbumsListBox.Items);
this.Close();
}
else
{
MessageBox.Show("No room for new album.");
this.Close();
}
}
Your problem (from your comments) is that your for loop's condition is incorrect. Your for loop is this:
for (int i = 0; i < MusicCollection.FormMain.MAX_ALBUMS; ++i)
There is one problem and one potential problem here. First, when this code is actually run, it's really running:
for (int i = 0; i < 100; ++i)
because MusicCollection.FormMain.MAX_ALBUMS is declared as 100. This causes an error when the length of MusicCollection.FormMain.PublicVars.AlbumList is less than 100, because you're trying to grab an index that doesn't exist.
Instead, you need to iterate from i=0 to the length of ....PublicVars.AlbumList-1, or, preferably, for(int i = 0; i < ....PublicVars.AlbumList.Count; i++).
The second potential problem is that you are potentially skipping index 0. Arrays start at index zero and continue to index length-1. As such, you probably want i++, not ++i. Depends on your implementation, though.

Categories

Resources