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!