0
Hello
I’m a beginner in C# and have a combobox receiving data from mysql:
mConn.Open();
MySqlCommand command = new MySqlCommand("select modelonome from modelo", mConn);
MySqlDataAdapter da = new MySqlDataAdapter(command);
DataTable dtModelos = new DataTable();
da.Fill(dtModelos);
cbModelo.DisplayMember = "modelonome";
cbModelo.ValueMember = "modelocod";
cbModelo.DataSource = dtModelos;
I created a method to save in the database:
public void salvar(Config config)
{
mConn = new MySqlConnection("Persist Security Info=False; server=localhost;database=****;uid=****;password=*****");
string comandosql = "INSERT INTO SETUP(setcanal,setporta,setlinha,setposto,setmodelo)" +
"VALUES(@setcanal,@setporta,@setlinha,@setposto,@setmodelo)";
MySqlCommand command1 = new MySqlCommand(comandosql, mConn);
command1.Parameters.AddWithValue("@setcanal",config.Setcanal);
command1.Parameters.AddWithValue("@setporta", config.Setporta);
command1.Parameters.AddWithValue("@setlinha", config.Setlinha);
command1.Parameters.AddWithValue("@setposto", config.Setposto);
command1.Parameters.AddWithValue("@setmodelo", config.Setmodelo);
try
{
mConn.Open();
int regitrosAfetados = command1.ExecuteNonQuery();
}
catch (MySqlException ex)
{
throw new ApplicationException(ex.ToString());
}
finally
{
mConn.Close();
}
}
}
And I’m calling him on my canvas in the boot:
ConfigDB configDB = new ConfigDB();
Config config = new Config(int.Parse(tbCanal.Text), int.Parse(tbPorta.Text), Convert.ToInt32(cbLinha.SelectedValue), Convert.ToInt32(cbPosto.SelectedValue), Convert.ToInt32(cbModelo.SelectedValue));
configDB.salvar(config);
MessageBox.Show("Registro salvo com sucesso!");
But it always gives the error: "Unable to cast Object of type" and not saved Does anyone know what it might be? What would be the right way to save? Or at least how to get the name that is displayed? I’ve tried using Selecteditem.toString(); but it returns the name Datarowview something like this.
some data cannot be converted... first need to know what infomation is generating the "Unable to cast Object of type". first put the values in individual variables to identify the problem, for example
var canal=int.Parse(tbCanal.Text);
... and so on, see if they all convert right and match the type of data in the table. Attention numbers with thousands and comma and dates, doing so will find the problem– Ricardo Pontual
Hello. then tbCanal is a textbox he saves normal, is not in it giving cast problem, is in the combobox cbLine, cbPost and cbModel
– Tais Nayara
then see how to properly convert these values, check the values of
SelectedValue
and you’ll be able to solve ;)– Ricardo Pontual
Unpack the code and see which exact point is giving error, it is easier to debug.
– user178974