I have a question about converting types. I want to change the currently selected combobox value string to an int, but I get errors
My code:
int.Parse(age.SelectedItem.ToString());
What can I do for this problem?
Ok now we know the error, you can check for a null value before trying to parse it using:
if (comboBox1.SelectedItem != null)
{
int x = int.Parse(comboBox1.SelectedItem.ToString());
}
else { //Value is null }
You can avoid a null value being passed by setting the text property of the control to what ever default value you want.
If you are still not getting a value after making sure one is selected you really need to post your code.
TryParse is a good method for this sort of thing:
int value;
if (!Int32.TryParse(this.comboBoxNumeric.Text, out value))
{
//Do something fun...
}
Use a Convert.ToInt32 method. You can always use the databinding like this:
class A
{
public int ID{get;set;}
public string Name{get;set;}
}
cbo.DataSource = new A[]{new A{ID=1, Name="hello"}};
cbo.DisplayMember = "Name";
cbo.DisplayValue = "ID";
int id = Convert.ToInt32(cbo.SelectedValue);
A a = (A) cbo.SelectedItem;
int a_id = a.ID;
int a_name = a.Name;
If you use LINQ to DataSets, develop is very easy for C# program.
try
{
string name = comboBoxPort.SelectedItem.ToString();
int portBaudrate = Convert.ToInt32(comboBoxBaudrate.SelectedItem);
}
//just solved
//enjoy
Related
EDIT:
Thanks to everyone who replied! I appreciate all of your answers :)
So I have a class with the following constructor:
public Transaction(DataRow row)
{
LastName = row.Field<string>("LastName");
FirstName = row.Field<string>("FirstName");
MI = row.ItemArray[3].ToString()[0];
ContactNumber = row.ItemArray[4].ToString();
Hours = int.Parse(row.ItemArray[5].ToString());
CheckIn = (DateTime)row.ItemArray[6];
roomNumber = int.Parse(row.ItemArray[9].ToString());
//Paid = row.Field<int>("Paid");
//TotalBill = row.Field<int>("TotalBill");
}
Notice I have 2 of them commented out with /'s That's because if I don't they return null values even if I try ''row.Field([Whatever]).GetValueOrDefault()'', it still comes out null and my constructor returns null. I also have my DB set with default values so IDK what's wrong.
Anyone got a work around? :)
The DataRow class has a method that is called IsNull and that could receive the column name.
Just combine it with the conditional operator
Paid = row.IsNull("Paid") ? 0 : row.Field<int>("Paid");
the same is true for all other fields that could contain a null value.
Just check for null first and supply a default value:
public Transaction(DataRow row)
{
LastName = row.Field<string>("LastName");
FirstName = row.Field<string>("FirstName");
MI = row.ItemArray[3].ToString()[0];
ContactNumber = row.ItemArray[4].ToString();
Hours = int.Parse(row.ItemArray[5].ToString());
CheckIn = (DateTime)row.ItemArray[6];
roomNumber = int.Parse(row.ItemArray[9].ToString());
Paid = row.Field<int?>("Paid") ?? 0;
TotalBill = row.Field<int?>("TotalBill") ?? 0;
}
See the ?? Operator (C# Reference) page on MSDN for further information on the ?? operator.
You can simply use the Nullable type and GetValueOrDefault method or use null coalescing operator.
Paid = row.Field<int?>("Paid").GetValueOrDefault()
or
Paid = row.Field<int?>("Paid") ?? 0
In both cases Paid will have a value of 0, you can change if you want.
Create your own little function that does a simple check.
Along the lines of:
public integer GetNumber (object val)
{
if (IsNumeric (val))
{
return val;
} else
{
return 0;
}
}
I'm not fantastic with C#, but that should give you an idea. Sorry about formatting, I'm on a phone which doesn't help at all.
i have valueMember in combobox and i need to save this value to integer...
This is my code:
public class Benzinky
{
public int B_cislo { get; set; }
public string Benzinka { get; set; }
}
var lines = File.ReadAllLines(#"C:...\pokus.txt");
var data = lines.Select(l => l.Split());
List<Benzinky> allB = data.Where(arr => arr.Length >= 2
&& arr[1].Trim().All(Char.IsDigit))
.Select(arr =>
new Benzinky
{
Benzinka = arr[0].Trim(),
B_cislo = int.Parse(arr[1].Trim())
})
.ToList();
var bindingSourceB = new BindingSource();
bindingSourceB.DataSource = allB;
comboBox1.DataSource = bindingSourceB;
comboBox1.ValueMember = "B_cislo";
comboBox1.DisplayMember = "Benzinka";
my txt:
Prague 3106
Berlin 3107
........
Have you any ideas?
You should convert the valueMember of comboBox1 to an integer and put the result in Number. This can be done in multiple ways, you can use Convert.ToInt32();
But I would take a look at Int32.Parse() and Int32.TryParse()
Int32.Parse
Number = Int32.Parse(comboBox1.ValueMember);
Above code should do the trick, but you will run in to troubles when the string doesn't contain a value that can be parsed to an integer, an exception will be thrown.
You could use Int32.TryParse if you would like to get a bool value in return instead of an exception.
Int32.TryParse
int Number;
bool result = Int32.TryParse(comboBox1.ValueMember, out Number);
if (result)
{
Console.WriteLine("Converted '{0}' to {1}.", comboBox1.ValueMember, Number);
}
else
{
//conversion failed
//Int32.Parse, would throw a formatexception here.
}
Could you try following code:
comboBox1.DataSource = bindingSourceB;
comboBox1.ValueMember = "B_cislo";
comboBox1.DisplayMember = "Benzinka";
int Number;
if(Int32.TryParse(comboBox1.ValueMember, out Number))
{
//Conversion succeeded
}
else
{
//Conversion failed, you should send a message to the user
//Or fill Number with a default value, your choice.
}
Sources:
MSDN Int32.Parse
MSDN Int32.TryParse
ValueMember is just used to determine the value of your combobox SelectedValue. To get the valueMember part of your ComboBox item, you have to cast the underlying item (which is of type Benzinky in your example) to the correct type and get the desired value from some property, here is how it should be done if you know the underlying data type and valueMember beforehand:
int x = ((Benzinky) comboBox1.Items[index]).B_cislo;
//or using dynamic
dynamic item = comboBox1.Items[index];
int x = item.B_cislo;
However if you want something dynamic (that happen when the valueMember may change prorammatically at some time), you have to use Reflection like this:
object item = comboBox1.Items[index];
var x = (int) item.GetType().GetProperty(comboBox1.ValueMember)
.GetValue(item, null);
NOTE: However the Reflection approach is applicable only when the DataSource of your comboBox is not some class like DataTable, because a DataTable exposes its Column name as ValueMember not any properties of it, the underlying item will be a DataRowView and so in that case the reflection code will fail.
I'm trying to update my table with this LINQ query
public void updateProduct(
int selectedIDToUpdate,
string prodNAMEToUp,
double prodPriceToUp,
string prodTYPEToUp,
int prodMANUToUp,
int prodCODEToUp)
{
DataClassesLINQEPOSDataContext dcld = new DataClassesLINQEPOSDataContext();
TBLPRODUCT tblprod = (from prod in dcld.TBLPRODUCTs
where prod.product_id == selectedIDToUpdate
select prod).First();
tblprod.product_name = prodNAMEToUp;
tblprod.product_price = prodPriceToUp;
tblprod.product_type = prodTYPEToUp;
tblprod.product_manufacturer = prodMANUToUp;
tblprod.product_code = prodCODEToUp;
dcld.SubmitChanges();
}
and then when I start to run the program I have this error
"InvalidCastException was unhandled"
"Specified cast is not valid."
Sorry I cant post image because I dont have enough reputation "points" :(
this is the control to pass the parameter on my class.
private void btnSaveToUpdate_Click(object sender, EventArgs e)
{
if (txtNameToUpdate.Text != "" ||
txtPriceToUpdate.Text != "" ||
txtTypeToUpdate.Text != "" ||
txtCodeToUpdate.Text != "")
{
Connection_Products update = new Connection_Products();
int selctedID = selectedIDToUpdate;
string prodNAMEToUp = txtNameToUpdate.Text;
double prodPriceToUp = double.Parse(txtPriceToUpdate.Text);
string prodTYPEToUp = txtTypeToUpdate.Text;
int prodMANUToUp = Convert.ToInt32(cmbManufacturerToUpdate.SelectedValue);
int prodCODEToUp = Convert.ToInt32(txtCodeToUpdate.Text);
update.updateProduct(selctedID, prodNAMEToUp, prodPriceToUp,
prodTYPEToUp, prodMANUToUp, prodCODEToUp);
}
else
{
MessageBox.Show("Error");
}
}
You most likely have some datatype mismatch between the values that you are trying to store and the data types of the columns in the database. This would be in one of the numeric columns.
If the prodPriceToUp column uses the money data type, this maps to a decimal type in Linq2Sql. You are trying to cast the double for the input parameter to decimal, which may be causing this issue. Try converting prodPriceToUp to a decimal before saving it.
I guess you are missing something in type mapping between updateProduct params and properties in tblprod. Please check here you are using correct types
This is because one of the following is trying to cast into an invalid type:
tblprod.product_name = prodNAMEToUp;
tblprod.product_price = prodPriceToUp;
tblprod.product_type = prodTYPEToUp;
tblprod.product_manufacturer = prodMANUToUp;
tblprod.product_code = prodCODEToUp;
Check for each of the these that the type of the left side is the same as the type of the right side. for example ensure that "tblprod.product_name" is a string property as you are trying to save a string to that property.
It is also possible that in your LINQ query, the where clause may have this problem, ensure that "prod.product_id" is an integer and not something else like a long or a short.
if these are all ok and you are still getting the exception then you will need to tell use what line is throwing the exception, and give use the details of the structure of tblprod;
I am currently using the following script to set this value as a String:
string ID = Request.QueryString["ID"].ToString();
However, I'd now like to store it as an Integer.
How do I do this?
Many thanks for any pointers.
Assuming you don't want to throw a server error on a bad string
int id=0;
if (int.TryParse(Request.QueryString["ID"],out id)) {
.. logic for valid id
} else {
.. logic for invalid id
}
int ID = int.Parse(Request.QueryString["ID"].ToString());
Use either of these:
If you know that you have an ID:
string ID = Request.QueryString["ID"];
int integerId = int.Parse(ID);
or, if the query string may be missing or invalid (never trust query strings....)
string ID = Request.QueryString["ID"];
int integerId;
if (int.TryParse(ID, out integerId))
{
// you have a valid integer ID here.
// process it
}
else
{
// handle missing or invalid ID
}
You could do something like:
int i = Convert.ToInt32(ID);
or
int i;
Int32.TryParse(ID, out i);
BTW Request.QueryString["ID"] is already a string so the following is fine:
string ID = Request.QueryString["ID"];
Try
int ID = int.Parse(Request.QueryString["ID"]);
See How can I convert String to Int?
You can do like this:
string ID = Request.QueryString["ID"].ToString();
int id=int.Parse(ID);
or
int id=Convert.ToInt16(ID);
Always use tryparse for querystring values if you want to convert it to integer even if you never set it to string , because user can change that anytime before sending request (visible in URL).
int id = 0 ;//default value
bool success = int.TryParse(Request.QueryString["ID"],out id))
if (success) {
//write code for default value action
return;
}
//write code for other values.
Howsit!
I encounter an error when i get a null value in my datareader.
public List<Complaint> View_all_complaints()
{
csDAL objdal= new csDAL();
List<Complaint> oblcomplist=new List<Complaint>();
using( IDataReader dr=objdal.executespreturndr("View_all_complaints"))
{
while (dr.Read())
{
Complaint objcomp= new Complaint();
populate_reader(dr,objcomp);
oblcomplist.Add(objcomp);
}
}
return oblcomplist;
}
public void populate_reader(IDataReader dr, Complaint objcomp)
{
objcomp.ref_num = dr.GetString(0);
objcomp.type = dr.GetString(1);
objcomp.desc = dr.GetString(2);
objcomp.date = dr.GetDateTime(3);
objcomp.housenum = dr.GetInt32(4);
objcomp.streetnum = dr.GetInt32(5);
objcomp.status = dr.GetString(6);
objcomp.priority = dr.GetString(7);
objcomp.cid = dr.GetInt32(8);
if (!dr.IsDBNull(9))
{
objcomp.resolved_date = dr.GetDateTime(9);
}
}
in sql resolved date allows null values, this is so because only when a complaint has been resolved , it must reflect that date otherwise it should be null.
if dr.getdatetime(9) is null then it must just set a string saying "Not Resolved"
please help!
You haven't shown what your Complaint type looks like, but basically you'll want to make sure that its resolved_date is of type DateTime? aka Nullable<DateTime>. That allows you to model a missing value elegantly.
As for displaying it - you haven't shown anything about where you display the data, but you'd want something like:
string text = complaint.ResolvedDate.HasValue ? complaint.ResolvedDate.ToString()
: "Not Resolved";
(I've changed this to use a property with the idiomatic name at the same time...)
IDataReader has a "IsDBNull" method, that should be called before calling GetXXX(), in case your value is not nullable.
For example:
objcomp.date = dr.GetDateTime(3);
should be:
objcomp.date = dr.IsDBNull(3) ? DateTime.MinValue : dr.GetDateTime(3);