Numeric value insert as 0 in accessdatabase - ms-access

I am creating one application where data are inserted into access table using DataGridView. The issue is that two value(s) are inserted correctly but when I'm trying to insert numeric value it's inserted as 0.
private void dataGridView1_RowLeave(object sender, DataGridViewCellEventArgs e)
{
try
{
if (dataGridView1.IsCurrentRowDirty)
{
string connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string cmd1 = "insert into Medicine_Available_Detail([Medicine_Name],[Dealer_name],[total_available])values(?,?,?)";
OleDbCommand cmd = new OleDbCommand(cmd1, con);
cmd.CommandType = CommandType.Text;
string Medicine_Name = dataGridView1.Rows[e.RowIndex].Cells["Medicine_Name"].Value.ToString();
cmd.Parameters.AddWithValue("#Medicine_Name", Medicine_Name);
string Dealer_name = dataGridView1.Rows[e.RowIndex].Cells["Dealer_name"].Value.ToString();
cmd.Parameters.AddWithValue("#Dealer_name", Dealer_name);
int Availability;
bool total_availableHasValue = int.TryParse(dataGridView1.Rows[e.RowIndex].Cells["total_available"].Value.ToString(), out Availability);
cmd.Parameters.AddWithValue("#total_available", Availability);
con.Open();
int n = cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("Data Inserted Successfully", "Data Inserted ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}

Presumably "Availability" is the numeric value. Are you sure that the value from the datagridview for total_available is numeric? If it's not, then Available will be = 0.
You could try testing total_availableHasValue after the parse or log/debug to check on the contents of the datagridview cell.

Related

Capture CheckBox list input- and assign to text area-

I am developing a web application using asp.net and MySQL. in my app, users can add recipes. It is a record that will be inserted. I have to input the ingredients in to the database as well. I am trying to capture the input ingredients ( which are in the form of checkboxes. ) Please review the GetIngredientsInput() method. I am checking which check boxes are checked, and saving the TEXT of the item checked. I want to capture the input in form of list. ( list of strings. ) I used StringBuilder for this, and assign it to a textarea control. But the code doesn't seem in effect. Thanks in advance.
protected void AddRecipe(object sender, EventArgs e)
{
GetIngredientsInput();
MySqlConnection con = new MySqlConnection("Server=localhost;Database=FreedomKitchen;Uid=root;Password=;");
con.Open();
String strcmd = "insert into Recipes(Recipe_ID,Food_Category,Meal_Category,Recipe_Name,All_Ingredients,Recipe_Description,Recipe_Instructions) values(#Recipe_ID,#Food_Category,#Meal_Category,#Recipe_Name,#All_Ingredients,#Recipe_Description,#Recipe_Instructions)";
MySqlCommand cmd = new MySqlCommand(strcmd, con);
MySqlCommand cmd_two = new MySqlCommand("select * from Recipes", con);
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = cmd_two;
DataSet ds = new DataSet();
da.Fill(ds, "Rows");
int row_count = ds.Tables["Rows"].Rows.Count;
r_id = row_count + 1;
cmd.Parameters.Add(new MySqlParameter("#Recipe_ID", r_id));
cmd.Parameters.Add(new MySqlParameter("#Food_Category", DropDownFoodCat.Text.ToString()));
cmd.Parameters.Add(new MySqlParameter("#Meal_Category", DropDownMealCat.Text));
cmd.Parameters.Add(new MySqlParameter("#Recipe_Name", txtRecipeName.Text));
cmd.Parameters.Add(new MySqlParameter("#All_Ingredients", txtAllIngredients.Text));
cmd.Parameters.Add(new MySqlParameter("#Recipe_Description", txtDescription.Text));
cmd.Parameters.Add(new MySqlParameter("#Recipe_Instructions", txtInstructions.Text));
cmd.ExecuteNonQuery();
con.Close();
}
public void GetIngredientsInput() {
foreach (ListItem li in CheckBoxListVeg.Items) {
if (li.Selected) {
String ing_name=li.Text.ToString();
str_ing_name.Append(ing_name);
str_ing_name.Append("\n");
txtAllIngredients.Text = ing_name = li.Text.ToString();
}
}
}
Try this :-
public string GetIngredientsInput()
{
StringBuilder str_ing_name = new StringBuilder();
foreach (ListItem li in CheckBoxListVeg.Items)
{
if (li.Selected)
{
String ing_name = li.Text.ToString();
str_ing_name.Append(ing_name);
str_ing_name.Append(",");
}
}
return str_ing_name.ToString();
}
protected void AddRecipe(object sender, EventArgs e)
{
txtAllIngredients.Text= GetIngredientsInput();
// Rest of code
}

How to store a Dictionary in a MySQL database?

Can some one demonstrate how I can save the values of a dictionary into a MySQL database?
public void Update()
{
Dictionary<string,int> t = new Dictionary<string,int>();
for(int i = 0; i < t.Count;i++)
{
//What comes Here?
}
}
First fix your iteration loop, second it is up to you to decide, eg:
MySqlConnection conDataBase = new MySqlConnection(constring);
conDataBase.Open();
foreach (KeyValuePair<string, string> entry in)
{
string constring = "..........";
string Query = "insert into Tablename values(#par1,#par2)";
MySqlCommand cmd = new MySqlCommand(Query, conDataBase);
cmd.Parameters.AddWithValue( "#par1",entry.Key)
cmd.Parameters.AddWithValue("#par2",entry.Value)
//Execute command
cmd.ExecuteNonQuery();
}

Iam not able to retrieve completely the data from sql?

public string getString()
{
con.ConnectionString = ConnString;
con.Open();
string sp = "select top 3 hotelid from hotel order by NEWID()";
SqlCommand cmd = new SqlCommand(sp, con);
SqlDataAdapter sa = new SqlDataAdapter(cmd);
cmd.ExecuteNonQuery();
reader = cmd.ExecuteReader();
while (reader.Read()) //Call Read to move to next record returned by SQL //OR call --While(reader.Read())
{
det = reader[0].ToString();
}
reader.Close();
con.Close();
return det;
}
When I'm executing this code I'm able to retrieve only a single item of data?,
but when I am executing the SQL query I am able to retrieve randomly 3 items of data.
You are overwriting the det variable on each while loop.
You either need to create a collection and add to it, or concatenate the string (note the +=)...
det += reader[0].ToString();
UPDATE
As suggested above, another option is to create a collection, something like...
public List<string> getString()
{
...
List<string> ret = new List<string>;
while (reader.Read())
ret.Add(reader[0].ToString());
...
return ret;
}

Access import into SQL server not importing first line

I am using a function to import data from a access db into SQL server:
public string importDataFromAccess(string table, string fileName)
{
OleDbConnection OleDbConn = new OleDbConnection(String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}", fileName));
try
{
string sSQLTable = table;
string myExcelDataQuery = "Select * from " + sSQLTable;
string sSqlConnectionString = connStr;
string sClearSQL = "DELETE FROM " + sSQLTable;
SqlConnection SqlConn = new SqlConnection(sSqlConnectionString);
SqlCommand SqlCmd = new SqlCommand(sClearSQL, SqlConn);
SqlConn.Open();
SqlCmd.ExecuteNonQuery();
SqlConn.Close();
OleDbCommand OleDbCmd = new OleDbCommand(myExcelDataQuery, OleDbConn);
OleDbConn.Open();
OleDbDataReader dr = OleDbCmd.ExecuteReader();
SqlBulkCopy bulkCopy = new SqlBulkCopy(sSqlConnectionString);
bulkCopy.DestinationTableName = sSQLTable;
while (dr.Read())
{
bulkCopy.WriteToServer(dr);
}
OleDbConn.Close();
return "Done";
}
catch (Exception ex)
{
OleDbConn.Close();
return ex.ToString();
}
}
I noticed it isnt importing the first record of each table, can anyone help notice why and how to fix? Hopefully it is only the first row...
You shouldn't need the
while (dr.Read())
{
bulkCopy.WriteToServer(dr);
}
And you just need to replace that with
bulkCopy.WriteToServer(dr);
The WriteToServer method
Copies all rows in the supplied IDataReader to a destination table
specified by the DestinationTableName property of the SqlBulkCopy
object.
But the dr.Read() that you have called has read the first line out of the Reader and advanced the IDataReader to the next record (so it is not accessible to the WriteServer method).

MySQL System.FormatException: Input string was not in a correct format

Currently, I am creating an application using ASP.NET MVC3 and MySQL and when I try to retrieve a user's first name from the databse I receive a System.FormatException: Input string was not in a correct format.
This is my code:
public string GetUserFirstName(UInt64 id)
{
DBConnections databaseCnnString = new DBConnections();
string connectionString = "server=123.123.com;user=me;database=db1;port=3306;password=abcdef";
MySqlConnection cnn = new MySqlConnection(connectionString);
try
{
cnn.Open();
string sp_GetFName = "SP_GET_FNAME";
MySqlCommand cmd = new MySqlCommand(sp_GetFName, cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("id", id);
cmd.Parameters["id"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("first_name", MySqlDbType.VarChar);
cmd.Parameters["first_name"].Direction = ParameterDirection.Output;
object result = cmd.ExecuteScalar();
if (result != null)
{
string fname = Convert.ToString(result);
return fname;
}
else
{
string fname = "friend";
return fname;
}
}
catch (Exception ex)
{
throw (ex);
}
finally
{
cnn.Close();
cnn.Dispose();
}
}
This is MySQL Stored Procedure:
CREATE DEFINER=`0001`#`%` PROCEDURE `SP_GET_FNAME`(IN id BIGINT(20), OUT first_name VARCHAR(60))
BEGIN
DECLARE user_id BIGINT(20) DEFAULT id;
DECLARE output VARCHAR(60);
SELECT `FName` FROM `users` WHERE USERID=user_id INTO output;
SET first_name = output;
END
The problem seems to be when executing cmd.ExecuteScalar().
What is my problem here?
Thank you in advance!
Copy and paste error on my part. The correct code that works as expected is:
public string GetUserFirstName(UInt64 id)
{
DBConnections databaseCnnString = new DBConnections();
string connectionString = "server=123.123.com;user=me;database=db1;port=3306;password=abcdef";
MySqlConnection cnn = new MySqlConnection(connectionString);
try
{
cnn.Open();
string sp_GetFName = "SP_GET_FNAME";
MySqlCommand cmd = new MySqlCommand(sp_GetFName, cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("id", id);
cmd.Parameters["id"].Direction = ParameterDirection.Input;
cmd.Parameters.Add(new MySqlParameter("first_name", MySqlDbType.VarChar));
cmd.Parameters["first_name"].Direction = ParameterDirection.Output;
cmd.ExecuteScalar();
string fname = Convert.ToString((cmd.Parameters["first_name"].Value));
return fname;
}
catch (Exception ex)
{
throw (ex);
}
finally
{
cnn.Close();
cnn.Dispose();
}
}
CORRECTION: cmd.Parameters.Add(new MySqlParameter("first_name", MySqlDbType.VarChar));
NOT: cmd.Parameters.AddWithValue("first_name", MySqlDbType.VarChar);
In my case, the FNAME field in the user table cannot be NULL; therefore, checking for NULL values returned in the code is not necessary.
I would guess that the user is not found or the fname is null.
And I really hope you're not querying the database for each user column.
Good luck.
An additional comment.
When trying to return a string value the AddWithValue appears to be trying to convert the output from a string into a number. This results in the string format exception.