Hello guys!
I'm working on a asp.net webshop and I'm also using this tutorial for the CMS management system.. But I have a problem with inserting the values into the database. As my database is different my code is quite different so I guess I should have made some other logical mistake in the code as there are no errors displayed when I launch the application in the browser! I'm talking about the Add_Product page.
The upload of the image function is working well and I have also added a dropdown list where the user should choose a category for the product, which is stored in another table of the MS SQL database, which is connected to the Products table. I would be very grateful if you can see where my mistake is as it is very important for me.
I post you the code..
The connection class:
public static class ConnectionClass
{
private static SqlConnection conn;
private static SqlCommand command;
static ConnectionClass()
{
String connectionString = ConfigurationManager.ConnectionStrings["WebShopDBSQLConnectionString"].ToString();
conn = new SqlConnection(connectionString);
command = new SqlCommand("", conn);
}
public static ArrayList GetProductsByType(string productType)
{
ArrayList list = new ArrayList();
string query = string.Format("select * from Products where category_id like '{0}'", productType);
try
{
conn.Open();
command.CommandText = query;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int product_id = reader.GetInt32(0);
string name = reader.GetString(1);
string description = reader.GetString(2);
int category_id = reader.GetInt32(3);
double price = reader.GetDouble(4);
string image = reader.GetString(5);
Product product = new Product(product_id, name, description, category_id, price, image);
list.Add(product);
}
}
finally
{
conn.Close();
}
return list;
}
public static void AddProduct(Product product)
{
string query = string.Format("insert into Products values('{0}', '{1}','{2}', @price,'{3}'", product.name , product.description , product.category_id , product.image);
command.CommandText = query;
command.Parameters.Add(new SqlParameter("@price", product.price));
try
{
conn.Open();
command.ExecuteNonQuery();
}
finally
{
conn.Close();
command.Parameters.Clear();
}
}
}
The product class:
public class Product
{
public int product_id { get; set; }
public string name { get; set; }
public string description { get; set; }
public int category_id { get; set; }
public double price { get; set; }
public string image { get; set; }
public Product(int product_id, string name, string description, int category_id, double price, string image)
{
this.product_id = product_id;
this.name = name;
this.description = description;
this.category_id = category_id;
this.price = price;
this.image = image;
}
public Product(string name, string description, int category_id, double price, string image)
{
this.name = name;
this.description = description;
this.category_id = category_id;
this.price = price;
this.image = image;
}
}
Add_product.aspx.cs file :
public partial class Add_product : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string selectedValue = ddlImage.SelectedValue;
ShowImages();
ddlImage.SelectedValue = selectedValue;
}
private void ShowImages()
{
// Получаване на всички адреси на изображения.
string[] images = Directory.GetFiles(Server.MapPath("/Images/"));
// Взимат се всички имена на файловете и се добавят в arraylist
ArrayList imageList = new ArrayList();
foreach (string image in images)
{
string imageName = image.Substring(image.LastIndexOf(@"\") + 1);
imageList.Add(imageName);
}
// Поставяме arrayList като datasource за dropdownview и обновяваме.
ddlImage.DataSource= imageList;
ddlImage.DataBind();
}
private void ClearTextFields()
{
TxtName.Text = "";
TxtDescription.Text = "";
TxtPrice.Text = "";
}
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
string filename = Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("/Images/") + filename);
lblResult.Text = "Изображение" + filename +" "+ " беше успешно качено.";
Page_Load(sender, e);
}
catch(Exception)
{
lblResult.Text= "Качването на изображението беше НЕУСПЕШНО.";
}
}
protected void btnClearFields_Click(object sender, EventArgs e)
{
ClearTextFields();
}
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
string name = TxtName.Text;
string description = TxtDescription.Text;
int category_id = Convert.ToInt32(DropDownList1.SelectedValue);
double price = Convert.ToDouble(TxtPrice.Text);
string image = "/Images/" + ddlImage.SelectedValue;
Product product = new Product(name, description, category_id, price, image);
ConnectionClass.AddProduct(product);
lblResult.Text = "Продуктът беше добавен успешно!";
ClearTextFields();
}
catch(Exception)
{
lblResult.Text = "Добавянето на продукта беше НЕУСПЕШНО!";
}
}
}
And the page code..
<%@ Page Title="" Language="C#" MasterPageFile="~/Management_Master.Master" AutoEventWireup="true" CodeBehind="Add_product.aspx.cs" Inherits="WebShopASP.Pages.Management.Add_product" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<style type="text/css">
.auto-style1
{
width: 80px;
}
.auto-style2
{
width: 80px;
height: 67px;
}
.auto-style3
{
height: 67px;
}
.auto-style4
{
width: 80px;
height: 55px;
}
.auto-style5
{
height: 55px;
}
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<h1> Добави нов продукт </h1>
<table cellspacing="15" class="productTable">
<tr>
<td class="auto-style1">
Име:</td>
<td>
<asp:TextBox ID="TxtName" runat="server" Width="300px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TxtName" ErrorMessage="*"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style1">
Описание:</td>
<td>
<asp:TextBox ID="TxtDescription" runat="server" Height="66px" TextMode="MultiLine" Width="303px"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style4">
Категория:</td>
<td class="auto-style5">
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1" DataTextField="category_name" DataValueField="category_id">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:WebShopDBSQLConnectionString %>" SelectCommand="SELECT DISTINCT [category_id], [category_name] FROM [Category] ORDER BY [category_name]"></asp:SqlDataSource>
</td>
</tr>
<tr>
<td class="auto-style1">
Цена:</td>
<td>
<asp:TextBox ID="TxtPrice" runat="server" Width="80px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="TxtPrice" ErrorMessage="*"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="auto-style2">
Изображение:</td>
<td class="auto-style3">
<asp:DropDownList ID="ddlImage" runat="server">
</asp:DropDownList>
<br />
<asp:FileUpload ID="FileUpload1" runat="server" Width="266px" />
<asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Качи изображение" Width="117px" CausesValidation="False" />
</td>
</tr>
</table>
<asp:Label ID="lblResult" runat="server" Text=""></asp:Label>
<br />
<asp:Button ID="btnClearFields" runat="server" Text="Изчисти полетата." OnClick="btnClearFields_Click" Width="135px" />
<asp:Button ID="btnSave" runat="server" Text="Запази" OnClick="btnSave_Click" />
</asp:Content>
I'd appreciate any type of help!
Thanks in advance!
Best regards
Gabriela