I want to assign a data to an int volunteerEducation if I Checked radio button to save it to the database!
int volunteerEducation;
switch (volunteerEducation)
case radioButton9.Checked:
volunteerEducation= 9;
break;
case radioButton10.Checked:
volunteerEducation = 10;
break;
try this...
foreach(Control c in this.Controls)
{
if(c is RadioButton)
{
RadioButton rbtn = (RadioButton)c;
// now here you can use if else statements or Switch Statement
}
}
switch allows you to check for one of several values on a single variable. if statements allow arbitrary conditions, which can check a single variable or many. Hence, switch is unsuited for what you are trying to do.
There are a few obvious options:
Use a series of if ... else if statements
Use some fancier construct such as a lookup dictionary mapping to methods (Dictionary<RadioButton,Func<>> might be a good place to start), though if you are unfamiliar with such constructs as switch I'd strongly recommend against that (it's the old "you have to learn to walk before you start to run")
Iterate over the radio buttons and do your magic inside a loop
Such a loop would look like:
foreach (Control c in this.Controls)
{
RadioButton rbtn = c as RadioButton;
if(rbtn != null)
{
// ... your code to work with 'rbtn' goes here ...
if (rbtn.Checked)
{
// ...
}
}
}
Using as rather than is followed by an explicit cast is idiomatic, and also saves you a cast; null checking is almost certainly faster, and certainly not slower, than casting. The as operator gives you null if the given value cannot be cast to the given type. In the case where the value of the variable you are working can be changed from another thread (not likely in this case, but possible in other cases), it also saves you the headache of a nigh-impossible-to-reproduce bug when something changes the value of the variable out under your feet.
A set of if statements to do the same thing would be along the lines of
if (radioButton9.Checked)
{
// do something
}
else if (radioButton10.Checked)
{
// do something
}
Using else if mimics the behavior of a switch ... case ... break construct. If they are independent, simply omit the else. (Then, I'd suggest adding a blank line between the end of the if statement-block and the next if statement, for readability.)
I found the Answer and it's not really different from thus answers.
the Point is to declare int. e.g int volunteerEducation = 0; then you have to use if ... else if.
private void updateButton_Click(object sender, EventArgs e)
{
try
{
string volunteerID = updtIDTextBox.Text;
string volunteerName = updtNameTextBox.Text;
string volunteerZone = updtZoneTextBox.Text;
string volunteerStreet = updtStreetTextBox.Text;
int volunteerSex = updtMaleRadioButton.Checked ? 0 : 1;
DateTime volunteerBirthday = updtBirthdayDateTimePicker.Value;
if (updtHomePhoneTextBox.Text == "")
updtHomePhoneTextBox.Text = "0";
int volunteerHomePhone = int.Parse(updtHomePhoneTextBox.Text);
if (updtWorkPhoneTextBox.Text == "")
updtWorkPhoneTextBox.Text = "0";
int volunteerWorkPhone = int.Parse(updtWorkPhoneTextBox.Text);
if (updtMobile1TextBox.Text == "")
updtMobile1TextBox.Text = "0";
int volunteerMobile1 = int.Parse(updtMobile1TextBox.Text);
if (updtMobile2TextBox.Text == "")
updtMobile2TextBox.Text = "0";
int volunteerMobile2 = int.Parse(updtMobile2TextBox.Text);
string volunteerEmail = updtEmailTextBox.Text;
string volunteerJob = updtJobTextBox.Text;
string volunteerAffiliation = updtAffiliationTextBox.Text;
//The solution start from here
int volunteerEducation = 0;
if (radioButton10.Checked)
volunteerEducation = 1;
else if (radioButton11.Checked)
volunteerEducation = 2;
else if (radioButton12.Checked)
volunteerEducation = 3;
else if (radioButton14.Checked)
volunteerEducation = 5;
else if (radioButton15.Checked)
volunteerEducation = 6;
else if (radioButton16.Checked)
volunteerEducation = 7;
else if (radioButton17.Checked)
volunteerEducation = 8;
else if (radioButton18.Checked)
volunteerEducation = 9;
//end solution
string volunteerEducationPlace = addEducationPlaceTextBox.Text;
string volunteerEducationDepartmen = addEducationDepartmentTextBox.Text;
//same above
int volunteerInteresting = 0;
if (updtIntrstMdcnRadioButton.Checked)
volunteerInteresting = 1;
else if (updtIntrstSosclRadioButton.Checked)
volunteerInteresting = 2;
else if (updtIntrstLrnRadioButton.Checked)
volunteerInteresting = 3;
else if (updtIntrstTrnRadioButton.Checked)
volunteerInteresting = 4;
//end
string volunteerNotes = addNotesTextBox.Text;
int x = dataGridViewX1.SelectedRows[0].Index;
UpdateVolunteer(volunteerID, volunteerName, volunteerZone, volunteerStreet, volunteerSex, volunteerBirthday, volunteerHomePhone, volunteerWorkPhone, volunteerMobile1, volunteerMobile2, volunteerEmail, volunteerJob, volunteerAffiliation, volunteerEducation, volunteerEducationPlace, volunteerEducationDepartmen, volunteerInteresting, volunteerNotes);
showVolunteers(x);
updtIDTextBox.Text = "";
updtNameTextBox.Text = "";
updtZoneTextBox.Text = "";
updtStreetTextBox.Text = "";
updtBirthdayDateTimePicker.Value = DateTime.Now;
updtHomePhoneTextBox.Text = "";
updtWorkPhoneTextBox.Text = "";
updtMobile1TextBox.Text = "";
updtMobile2TextBox.Text = "";
updtEmailTextBox.Text = "";
updtJobTextBox.Text = "";
updtAffiliationTextBox.Text = "";
updtEducationPlaceTextBox.Text = "";
updtEducationDepartmentTextBox.Text = "";
updtNotesTextBox.Text = "";
}
catch (SqlException sql)
{
MessageBoxEx.Show(sql.Message);
}
}
Related
I've been searching this page and other pages in this matter. I know it's not possible to get the data inside the while loop with direct assigning of variables, so I've tried to put it to label before and it works but only to the first value of the finalcred and finaldeb. It will not reset to fetch another value, so my real question is; Is there any other way to get the value inside the while loop and use it outside?
I have tried to declare it outside while and assign default value and the result will always be the default. It will not change.
r = t.NewRow();
//somecode..all good here
while (counterdate <= monthval)
{
//allgood in this part
totalcred = 0;
totaldeb = 0;
balance = 0;
crednum = 0;
debnum = 0;
if (readgetcode1.HasRows)
{
while (readgetcode1.Read())
{
readgetcred.Read();
readgetdeb.Read();
if (readgetdeb.HasRows)
{
debnum = Convert.ToDecimal(readgetdeb.GetValue(0));
}
else
{
debnum = 0;
}
if (readgetcred.HasRows)
{
crednum = Convert.ToDecimal(readgetcred.GetValue(0));
}
else
{
crednum = 0;
}
totalcred += crednum;
totaldeb += debnum;
if (strType == "Debit")
{
balance = totaldeb - totalcred;
}
else
{
balance = totalcred - totaldeb;
}
allbal += balance;
}
}
else
{
allbal = 0;
}
if (readprevCred.HasRows)
{
prevBalNum = Convert.ToDecimal(readprevBal.GetValue(0));
}
else
{
prevBalNum = 0;
}
if (strType == "Debit")
{
finaldeb = prevBalNum + allbal;
finalcred = 0;
}
else
{
finalcred = prevBalNum + allbal;
finaldeb = 0;
}
counterdate++;
}//while counterdate looping
r["accntCode"] = codevalue;
r["accntName"] = accntnameval;
r["DebitAmount"] = finaldeb;//this is the problem
r["CreditAmount"] = finalcred;;//this is the problem
t.Rows.Add(r);
//while readcodecheck in counter for code
This is the code used to check whether the first number is greater than the second, but it is not working as expected. Can anyone please suggest the reason and correct me?
if (txtFirst.Text == "")
{
txtFirst.Text = "0";
if (txtSecond.Text == "")
{
txtSecond.Text = "0";
int first = Convert.ToInt32(txtFirst.Text);
int second = Convert.ToInt32(txtSecond.Text);
if (first < second)
{
txtResult.Text = "TRUE";
}
else
{
txtResult.Text = "FALSE";
}
}
}
Your scenario is working only if both the textboxes are blank(""). so it will be much better if you do like the following:
if (txtFirst.Text == "") {txtFirst.Text = "0";}
if (txtSecond.Text == ""){txtSecond.Text = "0";}
// it is good to check for null in this scenario since
// Convert.ToInt32() is not capable of handling null
int first = Convert.ToInt32(txtFirst.Text);
int second = Convert.ToInt32(txtSecond.Text);
if (first < second){txtResult.Text = "TRUE";}
else{txtResult.Text = "FALSE";}
I want to be able to call the following function multiple times through out my code to fill different groups of 8 text boxes in my form.
Right now reference is being passed in "tbPlay" from where it is being called initially in the code.
Each time this function will be called it will be to fill different text box groups.
I am trying to think of a way of using the empty for loop to create the necessary variable names to replace tbPlay0-7 in my case statement, so it isn't only usable for one group of text boxes in my code. I am not sure it can be done.
Can anyone help.
private void convertBasetoDrawn(string numBase, string reference)
{
string baseNumber = numBase;
for (int i = 0; i < 8; i++)
{
//some code here to create variables to replace the text box names in the
//following case statement
}
switch (baseNumber)
{
case "000":
tbPlay0.Text = "000";
tbPlay0.ForeColor = Color.Red;
tbPlay1.Text = "500";
tbPlay2.Text = "050";
tbPlay3.Text = "005";
tbPlay4.Text = "550";
tbPlay5.Text = "505";
tbPlay6.Text = "055";
tbPlay7.Text = "555";
tbPlay7.ForeColor = Color.Red;
break;
}
}
Create a List<TextBox> for each group:
List<TextBox> list01 = new List<TextBox>() { tbPlay0, tbPlay1, ....};
List<TextBox> list02 = new List<TextBox>() { ..., ... , ....};
// ..
}
And pass such a group to the function:
private void convertBasetoDrawn(List<TextBox> list, string numBase, string reference)
{
string[] texts = new string[8]
{ "000", "500", "050", "005", "550", "505", "055", "555" };
for (int t = 0; t < list.Count; t++) list[t].Text = texts[t];
list[0].ForeColor = Color.Red;
list[7].ForeColor = Color.Red;
}
Assuming the texts will always look like that. If they depend on, maybe numbase you can construct them dynamically as well, as long as you know the rules.. Maybe even a simple replacement will do the job?
You didn't use reference, btw..
Now, I'm just guessig here, but maybe this is the pattern for your texts..:
string[] texts = new string[8]
{ "nnn", "dnn", "ndn", "nnd", "ddn", "dnd", "ndd", "ddd" };
for (int s = 0; s < texts.Length; s++)
texts[s] = texts[s].Replace("d", numBase).Replace("n", reference);
Now you can call it like this:
convertBasetoDrawn(list01, "0","5");
Update: For the rules as I understand them now you could do:
string newText = "";
for (int s = 0; s < texts.Length; s++)
{
newText = "";
for (int i = 0; i < 3; i++)
{
if (texts[s][i] == 'n') newText += numBase[i];
else newText += (Convert.ToByte(numBase[i].ToString()) +
Convert.ToByte(reference[0].ToString()) ).ToString("0");
}
texts[s] = newText;
}
and call it like this:
convertBasetoDrawn(list01, "001", "5");
or
convertBasetoDrawn(list02, "000", "1");
Note: no carry over here.. You'd have to define rules for that and code it yourself..
It's not clear how you plan to identify the specific group of eight. But let's assume you have somehow.
Then, if I were writing this code, I would use a UserControl to encapsulate the repeated pattern, exposing the eight TextBox controls — or rather, the properties of them that you want access to — as properties. E.g.
class TextBoxGroup : UserControl
{
public string Text1
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
public Color ForeColor1
{
get { return textBox1.ForeColor; }
set { textBox1.ForeColor = value; }
}
public string Text2
{
get { return textBox2.Text; }
set { textBox2.Text = value; }
}
public Color ForeColor2
{
get { return textBox2.ForeColor; }
set { textBox2.ForeColor = value; }
}
// ...
public string Text8
{
get { return textBox8.Text; }
set { textBox8.Text = value; }
}
public Color ForeColor8
{
get { return textBox8.ForeColor; }
set { textBox8.ForeColor = value; }
}
}
Then in your method, rather than whatever logic you planned on using to figure the starting index for your group, instead you just retrieve the appropriate TextBoxGroup instance and use it in the switch, like this:
case "000":
textBoxGroup.Text1 = "000";
textBoxGroup.ForeColor1 = Color.Red;
textBoxGroup.Text2 = "500";
textBoxGroup.Text3 = "050";
textBoxGroup.Text4 = "005";
textBoxGroup.Text5 = "550";
textBoxGroup.Text6 = "505";
textBoxGroup.Text7 = "055";
textBoxGroup.Text8 = "555";
textBoxGroup.ForeColor8 = Color.Red;
break;
A variation on the above would encapsulate the properties with setter methods taking an index. E.g.
class TextBoxGroup : UserControl
{
// Initialized in constructor to be the eight TextBoxes
private TextBox[] _textboxes;
public void SetText(int i, string text)
{
_textboxes[i].Text = text;
}
}
Of course, if you don't want to use a UserControl, you could just initialize a similar data structure in the main form instead, so that the controls can be accessed by index. But personally, I'd prefer the UserControl as it makes it easier to reuse and ensure consistency across all the groups of TextBox controls.
I'm still learning in programming
I'm trying to get customer data in list. So I can get the value from the index, but it only can get the first customer. the index won't increment, I'm still confusing, I have already move the variable for increment the index won't work, maybe my logic isn't right. here's the code, tell me where is not right..?? thank you for you help and explanation
public void getJamVSpot()
{
var listJamAwal = new List<String>();
var listJamAkhir = new List<String>();
var listNota = new List<int>();
DateTime tglSewa = dtp_tglSewa.Value.Date;
int r = 0;
String ja = String.Empty;
String jb = String.Empty;
int n = 0;
int indexUp = 0;
if (dtp_tglSewa.Value.Date == jl.getTglJadwalVspot(tglSewa, lap) && rdb_Lapangan_VSpot.Checked == true || rdb_rumputSintetis.Checked == true)
{
IEnumerator<String> jAwal = jl.getJamAwalbyDate(tglSewa, lap);
while (jAwal.MoveNext())
{
listJamAwal.Add(jAwal.Current);
}
IEnumerator<String> jAkhir = jl.getJamAkhirbyDate(tglSewa, lap);
while (jAkhir.MoveNext())
{
listJamAkhir.Add(jAkhir.Current);
}
IEnumerator<int> nota = jl.getNota(tglSewa, lap);
while (nota.MoveNext())
{
listNota.Add(nota.Current);
}
ja = listJamAwal[indexUp];
jb = listJamAkhir[indexUp];
n = listNota[indexUp];
int count = jl.countNota(n);
String penyewa = jl.getNamaPenyewa(n);
String no_kontak = jl.getNomorKontak(n);
String status = jl.getStatusSewa(n);
for (int i = 1; i <= count; i++)
{
foreach (DataGridViewRow row in dgv_Jadwal_Sewa.Rows)
if (row.Cells[0].Value.ToString().Equals(ja))
{
r = row.Index;
row.Cells[2].Value = penyewa;
row.Cells[3].Value = no_kontak;
row.Cells[4].Value = status;
if (ja != jb)
{
ja = jl.getJamAkhirbyJamAwal(ja);
row.Cells[2].Value = penyewa;
row.Cells[3].Value = no_kontak;
row.Cells[4].Value = status;
//dgv_Jadwal_Sewa.Rows[r].Selected = true;
}
break;
}
}
} indexUp++;
}
When you increment the indexUp variable you aren't using it anymore.
In your code you are just recovering the first item (0), doing some stuff with this value (in the loops) and exits.
For example, you can wrap your stuff with this loop:
for (int indexUp = 0; indexUp < listJamAwal.Count; indexUp++)
{
ja = listJamAwal[indexUp];
jb = listJamAkhir[indexUp];
n = listNota[indexUp];
int count = jl.countNota(n);
String penyewa = jl.getNamaPenyewa(n);
String no_kontak = jl.getNomorKontak(n);
String status = jl.getStatusSewa(n);
for (int i = 1; i <= count; i++)
{
foreach (DataGridViewRow row in dgv_Jadwal_Sewa.Rows)
{
if (row.Cells[0].Value.ToString().Equals(ja))
{
r = row.Index;
row.Cells[2].Value = penyewa;
row.Cells[3].Value = no_kontak;
row.Cells[4].Value = status;
if (ja != jb)
{
ja = jl.getJamAkhirbyJamAwal(ja);
row.Cells[2].Value = penyewa;
row.Cells[3].Value = no_kontak;
row.Cells[4].Value = status;
//dgv_Jadwal_Sewa.Rows[r].Selected = true;
}
break;
}
}
}
}
There are two problems with how you access the items:
You assign the variables outside the loop. That will get the values that the index points to at that moment, and changing the index variable later doesn't change what's assigned to the variables. You have to assign the variables inside the loop, except the count variable of course which you need before the loop starts.
You are incrementing the indexUp variable after the loop, when you have no use for it any more. You have to put that inside the loop so that it can be used in the next iteration to read new values into the variables.
I dont see any point of using first loop with "i" and then second with foreach. Its totally wrong - you are doing the same thing "count" times!
You also need to change penyewa, no_kontak, status because you are using same values inside loop
And in addition, I have never seen so confusing and unclear variable naming, you should change it if you want some else to use it :D
I'm geting a StackOverflowException. Somehow, posting here seemed appropriate.
I'm using Windows Forms in a C# application. This application is intended to run on Linux, FreeBSD and Mac-OS, so I can't use WPF, so please don't suggest it.
My guess is that I'm missing a nuance of WinForms, but I cant seem to figure out what.
The ComboBox is generated by the GUI form builder in VS 2010.
The specific lines of code that are throwing the error are here:
if(cur_num_is_valid)
{
cbx_material_num.Text = num;
}
else
{
num = "0";
//I only have one of the following two at a time. Both overflow
cbx_material_num.SelectedIndex = 0;
cbx_material_num.Text = "0";
}
Since the code is somewhat complex, here's the whole function code. 'cbx_' indicates a combo box. 'txtb_' is a text box.
private void cbx_material_numobj_SelectedIndexChanged(object sender, EventArgs e)
{
string obj = cbx_material_obj.Text;
string num = cbx_material_num.Text;
int selnum = 0;
int n = 0;
//do we need to recreate the numbers array?
bool cur_num_is_valid = false;
cbx_material_num.Items.Clear();
if(obj != lastobj)
{
n = m_demo.get_object_modifiers(obj);
for(int i = 0; i <= n; i++)
{
string s = i.ToString();
if(s == num && i < n) cur_num_is_valid = true;
cbx_material_num.Items.Add(s);
}
}
if(cur_num_is_valid)
{
cbx_material_num.Text = num;
}
else
{
num = "0";
//Overflow here:
cbx_material_num.SelectedIndex = 0;
}
try
{
selnum = int.Parse(num);
}
catch(Exception)
{
MessageBox.Show("Error, second select menu after 'object modifiers' must be a number, not '"+num+"'.");
cbx_material_num.Text="0";
return;
}
if(selnum >= n)
{
txtb_material_param1.Text = "0";
txtb_material_param2.Text = "0";
txtb_material_param3.Text = "0";
txtb_material_param4.Text = "0";
}
else
{
MaterialFace face;
MaterialParameter parameter;
int typeid;
object paramdata;
m_demo.get_object_modifiers_material(obj, selnum, out face, out parameter, out typeid, out paramdata);
cbx_material_face.Text = face.ToString();
cbx_material_paramtype.Text = parameter.ToString();
switch(typeid)
{
case 0:
txtb_material_param1.Text = ((float)paramdata).ToString();
cbx_material_datatype.Text = "float";
goto case -1;
case 1:
float[] parsf = ((float[])paramdata);
txtb_material_param1.Text = parsf[0].ToString();
txtb_material_param2.Text = parsf[1].ToString();
txtb_material_param3.Text = parsf[2].ToString();
txtb_material_param4.Text = parsf[3].ToString();
cbx_material_datatype.Text = "float[]";
break;
case 2:
txtb_material_param1.Text = ((int)paramdata).ToString();
cbx_material_datatype.Text = "int";
goto case -1;
case 3:
int[] parsi = ((int[])paramdata);
txtb_material_param1.Text = parsi[0].ToString();
txtb_material_param2.Text = parsi[1].ToString();
txtb_material_param3.Text = parsi[2].ToString();
txtb_material_param4.Text = parsi[3].ToString();
cbx_material_datatype.Text = "int[]";
break;
case -1: //can't actuall be returned, used to 'blank' the last three as '0'
txtb_material_param2.Text = "0";
txtb_material_param2.Text = "0";
txtb_material_param3.Text = "0";
break;
case 4:
OpenTK.Graphics.Color4 paramc = ((OpenTK.Graphics.Color4)paramdata);
txtb_material_param1.Text = paramc.R.ToString();
txtb_material_param2.Text = paramc.G.ToString();
txtb_material_param3.Text = paramc.B.ToString();
txtb_material_param4.Text = paramc.A.ToString();
cbx_material_datatype.Text = "Color4";
break;
default: //5
Vector4 paramv = ((Vector4)paramdata);
txtb_material_param1.Text = paramv.X.ToString();
txtb_material_param2.Text = paramv.Y.ToString();
txtb_material_param3.Text = paramv.Z.ToString();
txtb_material_param4.Text = paramv.W.ToString();
cbx_material_datatype.Text = "Vector4";
break;
}
}
}
You need to check that the SelectedIndex isn't already 0 before you try to set it:
if (cbx_material_num.SelectedIndex != 0){
cbx_material_num.SelectedIndex = 0;
}
Otherwise you're re-firing the event every time through.
I think that whenever you set this cbx_material_num.SelectedIndex = 0; within the EventHandler you invoke your
cbx_material_numobj_SelectedIndexChanged(object sender, EventArgs e)
Each call invokes another eventHandler so the stack fills up after some time.
Basically, the fact that it is called SelectedIndexChanged doesn't mean that the value has to be different from the previous one but that the value is set through its setter.