Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi, I am trying to get the data from a listview into the database:

try
{
SqlConnection conn = new SqlConnection(connstring)
conn.Open()
   
foreach(var item in listview1.Items)
{
using(SqlCommand command = new SqlCommand("INSERT INTO [User_Food] (FoodName,Calories,Quantity,Fat,Protein,Cards,Date)VALUES (@FoodName,@Calories,@Quantity,@Fat,@Protein,@Carbs,@Date)",conn)
{
command.Parameters.Add(new SqlParameter("@FoodName", FoodName));
command.Parameters.Add(new SqlParameter("@Calories", Calories));
command.Parameters.Add(new SqlParameter("@Quantity", Quantity));
command.Parameters.Add(new SqlParameter("@Fat", FatContent));
command.Parameters.Add(new SqlParameter("@Protein", ProteinContent));
command.Parameters.Add(new SqlParameter("@Carbs", CarbsContent));
command.Parameters.Add(new SqlParameter("@Date", datepicker1.SelectedDate));
command.ExecuteNonQuery();
}
conn.Close();
}
}
catch(Exception ex)
{
string message = ex.Message;
MessageBox.Show(message);
}



This code throws up the error:

"The parameterized query '(@FoodName nvarchar,@Calories int,@Quantity int, @Fat float' expects the parameter @'FoodName', which was not supplied."

Now to me it quite clearly is supplied it should be pulling the foodname from the listview items it is running through - I may have messed up something simple but I can't see my mistake! If someone coudl take a look would be much appreciated!

Dan

ObservableCollection FoodCollection = new ObservableCollection();
 
public ObservableCollection _FoodCollection {get { return FoodCollection;}} 

FoodCollection.Add(new FoodData { FoodName = foodNameTxt.Text, Calories = Convert.ToInt16(caloriesNum.Value), Quantity = Convert.ToInt16(quantityNum.Value), FatContent = fatNum.Value, ProteinContent = proteinNum.Value, CarbsContent = carbsNum.Value}); 

public class FoodData { 
public string FoodName {get; set} 
public int Calories {get; set;}
 public int Quantity {get;set;} 
public double FatContent {get;set;} 
public double ProteinContent {get;set;} 
public double CarbsContent {get;set;} }


XAML -
<gridviewcolumn displaymemberbinding="{Binding FoodName}" />
<gridviewcolumn displaymemberbinding="{Binding Calories}" />
....etc
 top of XAML :

DataContext="{Binding RelativeSource={RelativeSource Self}}"

<listview itemssource="{Binding _FoodCollection}">

</listview>


Each Column is binded to the above method.

Sorry about the editing on this I am having to type it out as I stupidly left my memory stick at home today!
Posted
Updated 24-Aug-11 23:43pm
v4

the value of FoodName in c# is NULL. How is FoodName set when not found in item?
read my article about disadvantages of sqlparameters.
Disadvantages of SqlParameters Turned into Advantages[^]

you need somethind like this:
C#
private static void CheckParameters(List&lt;SqlParameter&gt; sqlParameters)
    {
        foreach (SqlParameter parm in sqlParameters)
        {
            // when a parm.Value is null, the parm is not send to
            // the database so the stored procedure returns with the error
            // that it misses a parameter
            // it is very possible that the parameter should be null,
            // so when set it DBNull.Value the parameter
            // is send to the database

            if (parm.Value == null)
                parm.Value = DBNull.Value;
        }
    }

this sets NULL to DBNull.Value. Your parameter will be received in the Database now
 
Share this answer
 
v2
Comments
DanHodgson88 25-Aug-11 5:17am    
I think the problem is that I am not looking through the listview for the right things, I am telling it to look through the list of items and for every item insert certain params into the db. But how do you know which params are actually being taken from the item? My item has 7 params as you can see but I don't really understand how it is taking the value from each column of my listview and placeing it in the db. This is deffinetly from a lack of experience and im a bit stuck! Thanks again for you rhelp
Herman<T>.Instance 25-Aug-11 5:22am    
can you show me how your listview definition looks like?
DanHodgson88 25-Aug-11 5:24am    
Yup be 2 mins - I am on 2 comps so just copying across now - would you like the xaml also or just the code?
Herman<T>.Instance 25-Aug-11 5:28am    
xaml please
DanHodgson88 25-Aug-11 5:33am    
ObservableCollection<fooddata> FoodCollection = new ObservableCollection<fooddata>();

public ObservableCollection<fooddata> _FoodCollection
{get { return FoodCollection;}}

FoodCollection.Add(new FoodData
{
FoodName = foodNameTxt.Text,
Calories = Convert.ToInt16(caloriesNum.Value),
Quantity = Convert.ToInt16(quantityNum.Value),
FatContent = fatNum.Value,
ProteinContent = proteinNum.Value,
CarbsContent = carbsNum.Value});

public class FoodData
{
public string FoodName {get; set}
public int Calories {get; set;}
public int Quantity {get;set;}
public double FatContent {get;set;}
public double ProteinContent {get;set;}
public double CarbsContent {get;set;}
}

The XAML simply binds the columns of the viewlist to each of methods above within the FoodData section so:

<gridviewcolumn displaymemberbinding="{Binding FoodName}">

Hope that's enough info!
Seems like it should work, to me.
However if FoodName is null that may be causing your problem, try using FoodName ?? DBNull.Value. Note this is just a guess.

A small comment. You should put conn.Close(); in a finally-block. That way your connection is closed even if you get an exception.
C#
SqlConnection conn = null;
try
{
    conn = new SqlConnection(connstring);
    ...
}
finally
{
    if(conn != null)
        conn.Close();
}
 
Share this answer
 
Try using Parameters.AddWithValue instead:
C#
using(SqlCommand command = new SqlCommand("INSERT INTO [User_Food] (FoodName,Calories,Quantity,Fat,Protein,Cards,Date)VALUES (@FoodName,@Calories,@Quantity,@Fat,@Protein,@Carbs,@Date)",conn)
   {
   command.Parameters.AddWithValue("@FoodName", FoodName);
   command.Parameters.AddWithValue("@Calories", Calories);
   ...
 
Share this answer
 
Comments
Simon Bang Terkildsen 25-Aug-11 5:11am    
1 voted, hmm. Seems like a fine suggestion to me, +5 from me.
DanHodgson88 25-Aug-11 5:17am    
I just tried this mate and it didn't work but thanks for your help. Wasn't me who 1 voted by the way.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900