String was not recognized as a valid boolean in C# RadioButton - c#

I want to send values from one form to another form, which means when i click on a button then i want to send student values to another form through id column. However, I have got an error regarding string was not recognized when i want to send RadioButton values.
Please note, I do not save RadioButton values as string i.e. Male or Female into the database.
Here is the code itself.
if (this.isupdate)
{
DataTable dtStudentInfo = GetAllStudentInfoById(this.StudentId);
DataRow row = dtStudentInfo.Rows[0];
tbID.Text = row["std_id"].ToString();
tbName.Text = row["std_name"].ToString();
tbFatherName.Text = row["std_f_name"].ToString();
tbAddress.Text = row["std_address"].ToString();
tbBatchNo.Text = row["std_batch"].ToString();
tbBatchYear.Text = row["std_batch_year"].ToString();
tbCNIC.Text = row["std_cnic"].ToString();
tbMobNumber.Text = row["std_mob"].ToString();
rbMale.Checked = (row["std_gender"] is DBNull) ? false : Convert.ToBoolean(row["std_gender"] = 1) ? true : false);
}

A small typo makes a who lot of a difference.
Convert.ToBoolean(row["std_gender"] = 1)
Was meant to be (the convert is unnecessary here):
Convert.ToBoolean(row["std_gender"] == 1)
The typo caused the row["std_gender"] to be set to 1, which makes the convert fail.

Try
Convert.ToBoolean(row["std_gender"].ToString() == "1")

Solved..!!!
Code was right... Just a lil error with the returning type....
private object GetGender()
{
if (rbMale.Checked)
{
return (int)Gender.Male;
}
else if (rbFemale.Checked)
{
return (int)Gender.Female;
}
else
{
return (int)Gender.NoSelection;
}
}
Just changed the return type from object to int and also change the data type of gender from varchar to int...Here is the code
private int GetGender()
{
if (rbMale.Checked)
{
return (int)Gender.Male;
}
else if (rbFemale.Checked)
{
return (int)Gender.Female;
}
else
{
return (int)Gender.NoSelection;
}
}

Related

cannot implicity convert type int to 'string'

I'm getting this error and don't understand how to fix it
// validate user selected an item
if(cboCustomerInfo.SelectedIndex >-1)
{
// display items in groupbox
txtLastName.Text = Customers[cboCustomerInfo.SelectedIndex].Excursion;
if(Customers [cboCustomerInfo .SelectedIndex].Excursion ==1)
{
rdoNatureTrail.Checked = true;
}
else if (Customers[cboCustomerInfo .SelectedIndex ].Excursion ==1)
{
rdoBoatExcursion.Checked = true;
}
else
{
rdoKayakTour.Checked = true;
}
// endable groupbox
grpNatureExcursion.Enabled = true;
// set tag group box to index of job
grpNatureExcursion.Tag = cboCustomerInfo.SelectedIndex;
}
It errors on this statement:
txtLastName.Text=Customers[].Excursion
Any help would be greatly appreciated
what is the method Excursion from customer?? it returns a INT?
well you can cast the result with .toString();
> txtLastName.Text = Customers[cboCustomerInfo.SelectedIndex].Excursion.ToString();
it means exactly what it says, it can't implicitly convert an int to a string. Use ToString() to convert it

How to select a GuiComboBox Entry in SAP

I want to script our sap. Actually, I'm scripting the comboboxes. But I don't know, how to select a specific item.
SAPFEWSELib.dll included as refernece
public static bool SelectComboBoxItem(string ItemText)
{
int i = 0, ItInd = -1;
SAPFEWSELib.GuiComboBox GCB = GetComboBox(GFW, Criteria, Type); /*This function returns the SAPFEWSELib.GuiComboBox and works correctly*/
if (GCB != null)
{
foreach (SAPFEWSELib.GuiComboBoxEntry Entry in GCB.Entries)
{
if (Entry.Value.ToUpper().IndexOf(Item.ToUpper()) != -1)
{
/*How to select this Entry?*/
/*GCB.Entries.Item(Entry.Pos).Select() is a not contained methode*/
/*GCB.Entries.Item(Entry.Pos).Selected = true This functions for GuiTableRows and GuiGridViewRows, but not here*/
return true;
} else {
i++;
}
}
}else{
throw new System.Exception("ERROR: Unable to find combobox with current criteria!");
}
return false;
}
Does anybody has an Idea?
Ok, got it.
GCB.Value = Entry.Value;
In my testcase, the combobox was not changeable, so it never functioned.

Is there a way to use a variable in a catch block that was previously assigned in a try block?

So I've just been making a basic little calculator made up of buttons and a textbox(tbxSum).
The problem I'm having is that if an invalid sum is input I want my catch block to pick it up(which it does) and replace what's in the textbox with the most recent result in the calculator(which it doesn't).
So say I say:
3+3=6
My calculator will now put 6 in the textbox for the next sum.
So then say I did:
6//3
It's invalid which the calculator picks up, but I want the textbox value to return to 6 from the previous sum.
This is what I've tried:
var myButton = (Button)sender;
if (myButton.Content.ToString() == "=")
{
DataTable dt = new DataTable();
string s = tbxSum.Text;
string result = "";
if (s.Contains("("))
{
s = s.Replace("(", "*(");
}
try
{
var v = dt.Compute(s, "");
tbkSum.Text = s + "=" + v.ToString();
tbxSum.Text = v.ToString();
}
catch
{
MessageBox.Show("Invalid Sum");
tbxSum.Text = result;
}
}
I also have a textblock(tbkSum) which shows the previous sum so I thought maybe I could take everything in there to the right of the equals sign but I have no idea how to do that.
class Calculate(){
private boolean lastGoodValueSet = false;
private int lastGoodValue = 0;
void buttonFunction(){
if (myButton.Content.ToString() == "=")
{
//Your code
try
{
var v = dt.Compute(s, "");
tbkSum.Text = s + "=" + v.ToString();
lastGoodValue = v;
lastGoodValueSet = true;
}
catch
{
MessageBox.Show("Invalid Sum");
tbxSum.Text = result;
if (lastGoodValueSet)
tbxSum.Text = lastGoodValue;
}
}
}
}
This is an example set of code you could use, it's a simple value that you have to store to say if a good computation has been done and if so, at the point of error we want to go back to the computation. Hope that helps! You'll want to put some kind of message to the user, so they know there was an error though.
We have to do this, as at the point of the user pressing the equals button, the value has already changed inside tbkSum, we need it before the user has changed the value, so the best time to grab it is at the point when we update the tbkSum text value at a successful calculation
This is also assuming you do not create a new instance of the Calculate class each time you do your computation. Otherwise you'd need to store the number somewhere else
EDIT
The other way to fix this issue is to instead prevent the duplicate in the first place, I read from your other comments that you control what goes into the text box by buttons on the application. Assuming all buttons go through the same method of buttonFunction() then you could do:
private char[] buttonChars = {'/','*', '+'/*e.t.c*/}
void buttonFunction(){
string buttonPressedStr = myButton.Content.ToString();
char buttonPressed = buttonPressedStr[0];
int pos = Array.IndexOf(buttonChars , buttonPressed);
if (pos > -1)
{
if (tbxSum.Text.Length > 0){
char last = tbxSum.Text[tbxSum.Text.Length - 1];
pos = Array.IndexOf(buttonChars , last);
}
else
pos = 0;
if (pos > -1){
tbkSum.Text += buttonPressedStr;
}
}
There are cleaner ways to do this, but it's an example of how you could have prevented your issue in the first place. Some explanation:
buttonChars is an array of your different button types that would be appended to your text in the box, an example is +, -, and so on
First it checks if the button pressed was in your collection of specified buttonChars
If so, we have to check what the last thing added to the tbxSum was
If the last thing added to tbxSum was again found in the buttonChars array, we don't want to append a string
Otherwise, if the tbxSum was empty or had another character at the end, we can append our character
You can store the old value in a variable declard outside the try block and use this variable in your catch block again:
string oldSumValue = tbxSum.Text;
try
{
// your code
}
catch
{
tbxSum.Text = oldSumValue ;
MessageBox.Show("Invalid Sum");
}
Alternatively I've come up with this to prevent there being:
A)Duplicate of '*' or '/'
B)Sum starting with '*' or '/'
public MainWindow()
{
InitializeComponent();
if (tbxSum.Text == "")
{
btnDiv.IsEnabled = false;
btnMult.IsEnabled = false;
}
}
protected void btnSumClick(object sender, EventArgs e)
{
btnDiv.IsEnabled = true;
btnMult.IsEnabled = true;
var myButton = (Button)sender;
int pos = tbxSum.Text.Length;
if (pos > 0)
{
if ((tbxSum.Text[pos - 1] == '/' || tbxSum.Text[pos - 1] == '*') &&
(myButton.Content.ToString() == "/" || myButton.Content.ToString() == "*"))
{
int location = tbxSum.Text.Length - 1;
tbxSum.Text = tbxSum.Text.Remove(location, 1);
}
}
}

Convert Null value retrieving from database into decimal data type

Please check the Table below:
Scope is: I have to check in the database the top profileid and have to increase it by 1. If no data is there then it will fetch 0 and will increase it by 1.
I am getting the top value when there is data but in case the table is completely empty, I am getting exception. Code is as below.
public Decimal GetTopProfileID()
{
Decimal topID = 0;
var profileID = _dbContext.tblProfile.Max(n => n.profileid);
try
{
if (profileID == null)
{
topID = 1;
}
else
{
topID = Convert.ToDecimal(profileID);
topID++;
}
}
catch (Exception)
{
throw;
}
return topID;
}
Please help me find the solution. Ready for any question.
Thanks in advance !!
When there's no record in the table and you try to get .Max() value,
then it will throw an error, so its better to verify if any record
exist or not.
Update your code as follows.
if (_dbContext.tblProfile.Any()) {
//Verify records in tblProfile table, if there's any record exist or not
return Convert.ToDecimal(_dbContext.tblProfile.Max(n = > n.profileid)) + 1;
try {
if (profileID == null) {
topID = 1;
} else {
topID = Convert.ToDecimal(profileID);
topID++;
}
} catch (Exception) {
throw;
}
return topID;
} else { //If there's no value in table then assuming it should return 1.
return 1;
}
Update
Or you can make it more simpler:
if (_dbContext.tblProfile.Any()) {
//Verify records in tblProfile table, if there's any record exist or not
return Convert.ToDecimal(_dbContext.tblProfile.Max(n = > n.profileid)) + 1;
} else { //If there's no value in table then assuming it should return 1.
return 1;
}
You can use this code:
if (_dbContext.tblProfile.Any())
{
//Verify records in tblProfile table, if there's any record exist or not
var profileID = _dbContext.tblProfile.Max(n = > n.profileid) ?? 0;
return profileID + 1;
}
else
return 1;
Also if ProfileID is not nullable then don't need care about null value.
Then you can use below code:
return _dbContext.tblProfile.Any() ? _dbContext.tblProfile.Max(n = > n.profileid) + 1 : 1;
var profileID = _dbContext.tblProfile.OrderByDescending(n => n.profileid).FirstOrDefault();
Decimal topID = 1;
if (profileID != null)
{
decimal.TryParse(profileID.ProfileId, out topID);
topID++;
}
return topID;
}
Above answer by Moksh Shah is correct, but in that case we are hitting Data Base twice,
I think this should produce the desired result.
Use LastOrDefault() like this:
decimal variableName = Convert.ToDecimal(_dbContext.tblProfile.Select(x=> x.ProfileId).LastOrDefault() + 1);
Should work.
This is better than other solution as there is only one database call.

C# If Statement with value from field in Table

How do I write this statement to get a value back from the database or table and validate that if the Value = Yes it will return the "Result =10" part. The field is called "ApprovedStatus" the value will either be "No" or "Yes".
Visual Studio Tells me this: "The name 'Yes' does not exist in the current context"
If (ApprovedStatus.Equals = Yes)
{
result = 10;
}
else
{
result = 1;
}
Try if (ApprovedStatus == "Yes") if it's a string, or if (ApprovedStatus) if it's a bool.
If ApprovedStatus is of type bool, do:
if (ApprovedStatus)
Should it be string, do NOT do this
if(ApprovedStatus == "Yes")
because this will equal false if ApprovedStatus = "yes"
Instead use
if(StringComparer.OrdinalIgnoreCase.Equals(ApprovedStatus,"Yes"))
result = 10;
else
result = 1;
Note that if you do
if (ApprovedStatus.ToString().ToUpper().Equals("YES"))
or
if( ApprovedStatus.Equals("whatever",StringComparison.OrdinalIgnoreCase))
it will throw a null reference exception if ApprovedStatus is null.
...which is possible to likely if the value comes from a database.
Best guess given the limited info available... (Assuming ApprovedStatus is a String)
if(ApprovedStatus == "Yes")
{
result = 10;
}
else
{
result = 1;
}
or
if(ApprovedStatus.Equals("Yes"))
{
result = 10;
}
else
{
result = 1;
}
Use String.Compare -- it's more efficient.
if(String.Compare(ApprovedStatus, "Yes", true)==0){
result = 10;
} else {
result = 1;
}
Boolean values in C# are true and false. You should consult a basic C# tutorial, but your check has probably to look like this:
if (ApprovedStatus)
{
result = 10;
}
else
{
result = 1;
}
It can be written shorter as:
result = ApprovedStatus ? 10 : 1;
if (ApprovedStatus.Equals("Yes")) <-- Case Sensitive
{
}
or
if (ApprovedStatus.ToString().ToUpper() == "YES")
{
}

Categories