I want to sort a drop down list by price but it doesn't work. I have the error like the following:
Incorrect syntax near '='.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details:
System.Data.SqlClient.SqlException: Incorrect syntax near '='. Source
Error: Line 72: reader = cmd.ExecuteReader();
Here are my codes
New Arrivals.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class NewArrivals : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
bindDropDownList();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
bindDropDownList();
}
public void bindDropDownList()
{
DropDownList1.DataTextField = "price";
DropDownList1.DataSource = getReader();
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("-Select-"));
DropDownList1.Items.Insert(1, new ListItem("Price - Highest to Lowest"));
DropDownList1.Items.Insert(2, new ListItem("Price - Lowest to Highest"));
}
public SqlDataReader getReader()
{
SqlDataReader reader = null;
DataTable DataList1 = new DataTable();
if(DropDownList1.Text == "-Select-")
{
SqlConnection myConnect = new SqlConnection();
myConnect.ConnectionString = ConfigurationManager.ConnectionStrings["ProductCS"].ConnectionString;
string strCommandText ="SELECT * FROM [tb_ListPdts] WHERE newPdt=1";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
cmd.CommandText = strCommandText;
cmd.Connection = myConnect;
myConnect.Open();
reader = cmd.ExecuteReader();
DataList1.Load(reader);
myConnect.Dispose();
cmd.Dispose();
}
else if (DropDownList1.SelectedValue == "Price - Highest to Lowest")
{
SqlConnection myConnect = new SqlConnection();
myConnect.ConnectionString = ConfigurationManager.ConnectionStrings["ProductCS"].ConnectionString;
string strCommandText = "SELECT [image], [productName], [price], [newPdt] FROM [tb_ListPdts] WHERE newPdt==1 ORDER BY price desc";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
cmd.CommandText = strCommandText;
cmd.Connection = myConnect;
myConnect.Open();
reader = cmd.ExecuteReader();
DataList1.Load(reader);
myConnect.Dispose();
cmd.Dispose();
}
else if (DropDownList1.DataTextField == "Price - Lowest to Highest")
{
SqlConnection myConnect = new SqlConnection();
myConnect.ConnectionString = ConfigurationManager.ConnectionStrings["ProductCS"].ConnectionString;
string strCommandText = "SELECT [image], [productName], [price], [newPdt] FROM [tb_ListPdts] WHERE newPdt==1 ORDER BY price asc";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
cmd.CommandText = strCommandText;
cmd.Connection = myConnect;
myConnect.Open();
reader = cmd.ExecuteReader();
DataList1.Load(reader);
myConnect.Dispose();
cmd.Dispose();
}
return reader;
}
}
New Arrivals.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="NewArrivals.aspx.cs" Inherits="NewArrivals" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<style type="text/css">
.style2
{
width: 80%;
}
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<p id="product">New Products</p>
<hr />
<br />
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" AppendDataBoundItems="true"
onselectedindexchanged="DropDownList1_SelectedIndexChanged" >
<asp:ListItem>-Select-</asp:ListItem>
<asp:ListItem>Price - Highest to Lowest</asp:ListItem>
<asp:ListItem>Price - Lowest to Highest</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<table class="style2" id="newTable" rules="groups">
<tr>
<td>
</td>
</tr>
<tr>
<td>
<asp:DataList ID="DataList1" runat="server" BackColor="#DEBA84"
BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3"
CellSpacing="2" GridLines="Both"
RepeatColumns="3" RepeatDirection="Horizontal">
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<ItemStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<ItemTemplate>
<asp:Image ID="Image1" ImageUrl= '<%# Eval("image") %>'
runat="server" Height="180px" Width="230px" />
<br />
<asp:Label ID="productNameLabel" runat="server"
Text='<%# Eval("productName") %>' />
<br />
Price: $
<asp:Label ID="priceLabel" runat="server" Text='<%# Eval("price") %>' />
<br />
<asp:Label ID="newPdtLabel" runat="server" Text='<%# Eval("newPdt") %>' Visible="False" />
<br />
<br />
</ItemTemplate>
<SelectedItemStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
</asp:DataList>
</td>
</tr>
</table>
</asp:Content>
Your select statement is wrong. You are using equal comparator as == in your where clause. SQL Server T-SQL does not use C-style equals, instead a single = operator is used.
Update this statement
FROM [tb_ListPdts] WHERE newPdt==1 ORDER BY price asc
to use a single = operator as below:
FROM [tb_ListPdts] WHERE newPdt=1 ORDER BY price asc
Related
I'm trying to insert a record into a SQL Server 2014 database using ASP.NET with C#.
I have implemented a session for my gridview data, and I'm trying to insert that session into the database, but when I click the button "book", only the top URL changes:
Database:
The record isn't getting inserted into the database nor my Label (Errorm) is changing to gg.
.aspx file:
<%# Page Title=""
Language="C#"
MasterPageFile="~/Main.Master"
AutoEventWireup="true"
CodeBehind="hotels.aspx.cs"
Inherits="Hotel_Mangement.hotels" %>
<asp:Content ID="Content1" ContentPlaceHolderID="hotels" runat="server">
<div class="destinations">
<div class="destination-head">
<div class="wrap">
<h3>Hotels</h3>
</div>
<!-- End-destinations -->
<div class="find-place dfind-place">
<div class="wrap">
<div class="p-h">
<span>FIND YOUR</span>
<label>HOTEL</label>
</div>
<!-- strat-date-picker -->
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
$(function () {
$("#<%= txtstart.ClientID %>").datepicker();
});
</script>
<!-- /End-date-picker -->
<!-- strat-date-picker -->
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
$(function () {
$("#<%= txtend.ClientID %>").datepicker();
});
</script>
<!---/End-date-piker---->
<div class="p-ww">
<form>
<span> City or Area</span>
<asp:DropDownList ID="dl1" runat="server" class="dest" required="This field cannot be blank">
<asp:ListItem Selected="True">Location</asp:ListItem>
<asp:ListItem>Mumbai</asp:ListItem>
<asp:ListItem>Goa</asp:ListItem>
<asp:ListItem>Delhi</asp:ListItem>
<asp:ListItem>Ahmedabad</asp:ListItem>
<asp:ListItem>Jammu</asp:ListItem>
<asp:ListItem>Jharkhand</asp:ListItem>
<asp:ListItem>Kerala</asp:ListItem>
<asp:ListItem>Bhuj</asp:ListItem>
<asp:ListItem>Bengaluru</asp:ListItem>
<asp:ListItem>Kalyan</asp:ListItem>
</asp:DropDownList><br />
<br /><span> Check-in</span>
<asp:TextBox ID="txtstart" runat="server" class="date" required="This field cannot be blank"></asp:TextBox>
<span> Check-out</span>
<asp:TextBox ID="txtend" runat="server" class="date" required="This field cannot be blank"></asp:TextBox><br /> <br />
<span> Number of rooms</span>
<asp:DropDownList ID="dlrooms" runat="server" required="This field cannot be blank">
<asp:ListItem Selected="True">Select number of rooms</asp:ListItem>
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
</asp:DropDownList><br /><br />
<span> Number of members</span>
<asp:DropDownList ID="dlmumbers" runat="server" required="This field cannot be blank">
<asp:ListItem Selected="True">Select number of members per room</asp:ListItem>
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>5</asp:ListItem>
<asp:ListItem>6</asp:ListItem>
</asp:DropDownList>
<br /> <br />
<asp:Button ID="Button1" runat="server" Text="Search" OnClick="Button1_Click" />
</form>
</div>
<div class="clear"> </div>
</div>
</div>
<!----//End-find-place---->
</div>
<div class="criuse-main">
<div class="wrap">
<div class="criuse-head1">
<h3>CHEAPEST HOTELS</h3>
</div>
</div>
</div>
<asp:SqlDataSource ID="SqlDataSource1"
runat="server"
ConnectionString='<%$ ConnectionStrings:RegisterConnectionString15 %>'
SelectCommand="SELECT * FROM [hotels_main]"></asp:SqlDataSource>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1" >
<ItemTemplate>
<div ID="div1" runat="server">
<div class="criuse-main" >
<div class="wrap">
<div class="criuse-grids">
<div class="criuse-grid">
<div class="criuse-grid-head">
<div class="criuse-img">
<div class="criuse-pic">
<asp:Image ID="Image1" runat="server" ImageUrl='<%#Eval("ImagePath") %>' Height="350px" width="1000px"/>
</div>
<div class="criuse-pic-info">
<div class="criuse-pic-info-top">
<div class="criuse-pic-info-top-weather">
<p>33<label>o</label><i>c</i><span> </span></p>
</div>
<div class="criuse-pic-info-top-place-name">
<h2><span><%#Eval("hotel_location") %></span></h2>
</div>
</div>
<div class="criuse-pic-info-price">
<p><span>Starting From</span> <h4><%#Eval("price") %> $</h4></p>
</div>
</div>
</div>
<div class="criuse-info">
<div class="criuse-info-left">
<ul>
<li><a class="c-hotel" href="#"><span> </span><%#Eval("rooms_available") %></a></li>
<li><a class="c-air" href="flight.aspx"><span> </span> Air Ticket</a></li>
<li><a class="c-fast" href="#"><span> </span> Guest per room:<%#Eval("max_guest") %></a></li>
<li><a class="c-car" href="#"><span> </span> Car for All transfers</a></li>
<div class="clear"> </div>
</ul>
</div>
<div class="clear"> </div>
</div>
</div>
<div class="criuse-grid-info">
<h1> <a href="hotels_main.aspx?id=<%#Eval("hotel_id") %>" ><%#Eval("hotel_name") %></a></h1>
<p><%#Eval("s_desc") %> </p>
</div>
</div>
</div>
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
<center>
<div>
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" class="myGridClass" AutoGenerateColumns="False">
<AlternatingRowStyle BackColor="White" />
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
<Columns>
<asp:TemplateField HeaderText="HotelName">
<ItemTemplate>
<asp:Label ID="lblhotelname" runat="server" Text='<%# Bind("hotel_name") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="HotelLocation">
<ItemTemplate>
<asp:Label ID="lblhotellocation" runat="server" Text='<%# Bind("hotel_location") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="lblprice" runat="server" Text='<%# Bind("price") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="Label1" runat="server" Text="Label" Visible="False"></asp:Label>
<br />
<form>
<asp:Button ID="book" runat="server" Text="Book now" class="d-next" OnClick="book_Click" />
</form>
<asp:Label ID="lprice" runat="server" Text="Label" Visible="False"></asp:Label>
<asp:Label ID="lcheckin" runat="server" Text="Label" Visible="False"></asp:Label>
<asp:Label ID="lcheckout" runat="server" Text="Label" Visible="False"></asp:Label>
<asp:Label ID="lmembers" runat="server" Text="Label" Visible="False"></asp:Label>
<asp:Label ID="lrooms" runat="server" Text="Label" Visible="False"></asp:Label>
<br />
<asp:Label ID="Errorm" runat="server" Text="Label"></asp:Label>
</div>
</center>
</div>
</asp:Content>
.aspx.cs code-behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace Hotel_Mangement
{
public partial class hotels : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source=RISHIK\SQLEXPRESS;Initial Catalog=Register;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
GridView1.Visible = false;
/* div1.Visible = true; */
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from hotels_main";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
book.Visible = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
string query =
"select hotel_name, hotel_location ,price from hotels_main where hotel_location='" +
dl1.Text + "' ";
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
GridView1.Visible=true;
con.Close();
if (ds.Tables[0].Rows.Count == 0)
{
Label1.Visible = true;
Label1.Text = "No data found";
book.Visible = false;
}
else
{
/* div1.Visible = true;*/
Label1.Visible = false;
book.Visible = true;
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new System.Data.DataColumn("HotelName", typeof(String)));
dt.Columns.Add(new System.Data.DataColumn("HotelLocation", typeof(String)));
dt.Columns.Add(new System.Data.DataColumn("Price", typeof(String)));
foreach (GridViewRow row in GridView1.Rows)
{
Label lblhotelname = (Label)row.FindControl("lblhotelname");
Session["hotelname"] = lblhotelname.Text;
Label lblhotellocation = (Label)row.FindControl("lblhotellocation");
Session["hotelocation"] = lblhotellocation.Text;
Label lblprice = (Label)row.FindControl("lblprice");
Session["price"] = lblprice.Text;
dr = dt.NewRow();
dr[0] = lblhotelname.Text;
dr[1] = lblhotellocation.Text;
dr[2] = lblprice.Text;
dt.Rows.Add(dr);
}
Session["check_in"] = txtstart.Text.ToString();
Session["check_out"] = txtend.Text.ToString();
}
}
/*private void SendGridInfo()
{
}
Session["GridData"] = dt; Response.Redirect("WebForm2.aspx");
} */
protected void book_Click(object sender, EventArgs e)
{
con.Open();
string insertQuery = "Insert into hotelbook_details values('" + Session["USER_ID"].ToString() + "','" + Session["hotelname"].ToString() + "','" + Session["hotelocation"].ToString() + "','" + Session["check_in"].ToString() + "','" + Session["check_out"].ToString() + "','" + Session["price"].ToString() + "')";
SqlCommand cmd1 = new SqlCommand(insertQuery, con);
cmd1.ExecuteNonQuery();
con.Close();
Errorm.Text = "gg";
}
}
}
The problem was the <form> ..... </form> tag in aspx. As I am using a master page I don't need it.
After removing all the form tags, it worked all fine.
Are you sure it is not saving? Have you checked your database?
Change your load page to:
if (IsPostBack == false){
GridView1.Visible = false;
/* div1.Visible = true; */
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from hotels_main";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
book.Visible = false;
}
When you click a button it will reload the form load. The code above will prevent it from loading when doing a post-back, that is, clicking a button.
I'm creating a website in ASP.NET (in c#) with campaigns listed into a datalist (seperated from each other by using a <div> in the datalist so each campaign is listed into a block).
I can't update a specific column in the Campaigns table via c# because it can't find the scalar variable #camp_id (the ID of the campaign).
I'm using this command to update:
sqlCmd = "UPDATE Campagnes SET camp_status=2 WHERE camp_id=#camp_id";
Someone who knows how to make it possible to update 'camp_status' to 2 by using the 'camp_id' so only the 'camp_status' of that specific campaign (and not from others in the datalist) will be updated?
Edit: this is my whole code I'm using:
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
string sqlConn;
string sqlCmd;
sqlConn = #"Data Source=my-ip,1433;Initial Catalog=DbName;
Integrated Security=False;user id=sa;password=password";
sqlCmd= "UPDATE Campagnes SET camp_status=2 WHERE camp_id=#camp_id";
conn.ConnectionString = sqlConn;
cmd.Connection = conn;
cmd.CommandText = sqlCmd;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
So as you can see I'm not using parameters yet because I don't know how to add this and how it reads the value from the database.
The full code I'm using at the moment:
SqlConnection conn2 = new SqlConnection();
SqlCommand cmd2 = new SqlCommand();
string sqlConn2;
string sqlCmd2;
sqlConn2 = #"Data Source=my-ip,1433;Initial Catalog=dbname;Integrated Security=False;user id=sa;password=password";
sqlCmd2 = "select * from Campagnes";
conn2.ConnectionString = sqlConn2;
cmd2.Connection = conn2;
cmd2.CommandText = sqlCmd2;
conn2.Open();
SqlDataReader dr = cmd2.ExecuteReader();
while (dr.Read())
{
id = dr.GetInt32(0);
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
string sqlConn;
string sqlCmd;
sqlConn = #"Data Source=my-ip,1433;Initial Catalog=dbname;Integrated Security=False;user id=sa;password=password";
sqlCmd = "UPDATE Campagnes SET camp_status=1 WHERE camp_id=" + id;
cmd.Parameters.AddWithValue("#camp_id", id);
conn.ConnectionString = sqlConn;
cmd.Connection = conn;
cmd.CommandText = sqlCmd;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
Can't upload my image right here so here an external link to the screenshot: http://i.imgur.com/P8MeKm4.png
As you can see in the image, all the seperated white blocks are one datalist, but seperated by a div that will be generated when a new campaign will be added. When we click the edit button in the bottom of the right, the camp_status needs to be set to 2 (so the admin knows that the campaign needs to be edited).
ASP Source:
div id="popUpPanel">
<p>Waarom vindt u dat deze campagne nog niet in orde is? Geef uw feedback hieronder in:</p>
<asp:TextBox ID="TextBox1" CssClass="box" TextMode="MultiLine" runat="server"></asp:TextBox>
<asp:Button ID="Button1" OnClick="Button1_Click" runat="server" Text="OK" />
</div>
<asp:DataList CellPading="5" ID="DataList1" runat="server" DataSourceID="SqlDataSource1" Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False" Font-Underline="False" style="margin-right: 0px" >
<ItemTemplate>
<div class="list" style="padding-left: 25px; padding-right: 10px; padding-top: 10px;">
<asp:Label ID="titelLabel" runat="server" style="font-size: xx-large" Text='<%# Eval("titel") %>' />
<br />
<asp:Label ID="Label1" runat="server" style="font-size: xx-large; display: none;" Text='<%# Eval("camp_id") %>' />
<asp:Label ID="datum_geplaatstLabel" runat="server" Text='<%# Eval("datum_geplaatst") %>' />
<br /><br />
<strong>Korte beschrijving:</strong><br />
<asp:Label ID="korte_beschrijvingLabel" runat="server" Text='<%# Eval("korte_beschrijving") %>' />
<br /><br />
<strong>Lange beschrijving:</strong><br />
<asp:Label ID="lange_beschrijvingLabel" runat="server" Text='<%# Eval("lange_beschrijving") %>' />
<br />
<table class="auto-style1">
<tr>
<td class="auto-style2"><strong>
<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/img/edit.png" OnClientClick="showPopUp(); return false;" Style="margin-left:9px;" />
</strong></td>
<td><strong>
<asp:ImageButton ID="ImageButton1" runat="server" asp:Imagebutt="" ImageUrl="~/img/vink.png" Style="margin-left:0px;" />
</strong></td>
</tr>
</table>
<br />
</div>
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:WebhoostConnectionString %>" SelectCommand="SELECT [titel], [datum_geplaatst], [korte_beschrijving], [lange_beschrijving], [camp_id] FROM [Campagnes]"></asp:SqlDataSource>
So when we click on the 'Button1' in the PopupPanel the camp_status needs to be set to 2 only of that specific campaign. As you can see in the source I was also trying to use the label I was talking about, but everytime a new div is created, all coming labels will have 'Label1' as ID so it will also pick all campaign ID's and not just one..
ASP source code (using the CommandArgument in the button):
<div id="popUpPanel">
<p>Waarom vindt u dat deze campagne nog niet in orde is? Geef uw feedback hieronder in:</p>
<asp:TextBox ID="TextBox1" CssClass="box" TextMode="MultiLine" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Submit" CommandArgument='<%= Campagnes.camp_id %>' />
</div>
<asp:DataList CellPading="5" ID="DataList1" runat="server" DataSourceID="SqlDataSource1" Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False" Font-Underline="False" style="margin-right: 0px" >
<ItemTemplate>
<div class="list" style="padding-left: 25px; padding-right: 10px; padding-top: 10px;">
<asp:Label ID="titelLabel" runat="server" style="font-size: xx-large" Text='<%# Eval("titel") %>' />
<br />
<asp:Label ID="Label1" runat="server" style="font-size: xx-large; display: none;" Text='<%# Eval("camp_id") %>' />
<asp:Label ID="datum_geplaatstLabel" runat="server" Text='<%# Eval("datum_geplaatst") %>' />
<br /><br />
<strong>Korte beschrijving:</strong><br />
<asp:Label ID="korte_beschrijvingLabel" runat="server" Text='<%# Eval("korte_beschrijving") %>' />
<br /><br />
<strong>Lange beschrijving:</strong><br />
<asp:Label ID="lange_beschrijvingLabel" runat="server" Text='<%# Eval("lange_beschrijving") %>' />
<br />
<table class="auto-style1">
<tr>
<td class="auto-style2"><strong>
<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/img/edit.png" OnClientClick="showPopUp(); return false;" Style="margin-left:9px;" />
</strong></td>
<td><strong>
<asp:ImageButton ID="ImageButton1" runat="server" asp:Imagebutt="" ImageUrl="~/img/vink.png" Style="margin-left:0px;" />
</strong></td>
</tr>
</table>
<br />
</div>
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:WebhoostConnectionString %>" SelectCommand="SELECT [titel], [datum_geplaatst], [korte_beschrijving], [lange_beschrijving], [camp_id] FROM [Campagnes]"></asp:SqlDataSource>
C# source code (edited EventArgs to CommandEventArgs e):
string id;
SqlConnection conn2 = new SqlConnection();
SqlCommand cmd2 = new SqlCommand();
string sqlConn2;
string sqlCmd2;
sqlConn2 = #"Data Source=81.169.242.73,1433;Initial Catalog=Webhoost;Integrated Security=False;user id=sa;password=63310Kw1c";
sqlCmd2 = "select * from Campagnes";
conn2.ConnectionString = sqlConn2;
cmd2.Connection = conn2;
cmd2.CommandText = sqlCmd2;
conn2.Open();
SqlDataReader dr = cmd2.ExecuteReader();
while (dr.Read())
{
id = e.CommandArgument.ToString();
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
string sqlConn;
string sqlCmd;
sqlConn = #"Data Source=81.169.242.73,1433;Initial Catalog=Webhoost;Integrated Security=False;user id=sa;password=63310Kw1c";
sqlCmd = "UPDATE Campagnes SET camp_status=1 WHERE camp_id=" + id;
cmd.Parameters.AddWithValue("#camp_id", id);
conn.ConnectionString = sqlConn;
cmd.Connection = conn;
cmd.CommandText = sqlCmd;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
You have to define and add the parameter #camp_id
cmd.Parameters.AddWithValue("#camp_id", youCampIdValue);
I am using SQL command to insert and delete into the grid but getting following errors while executing.
Error 1 Use of unassigned local variable 'cmd' (This is at INSERT INTO Table(ID,Summary) values ('" + Convert)
Error 2 'System.DateTime' does not contain a definition for 'Text'
Error 3 'System.EventArgs' does not contain a definition for 'CommandName' and no extension method 'CommandName' accepting a first argument of type 'System.EventArgs' could be found (are you missing a using directive or an assembly reference?)
Error 4 'System.EventArgs' does not contain a definition for 'CommandArgument' and no extension method 'CommandArgument' accepting a first argument of type 'System.EventArgs' could be found (are you missing a using directive or an assembly reference?)
Error 5 The name 'fillgrid' does not exist in the current context
The HTML part is correct . But I think I have not written the insert and delete function properly
This is the HTML code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title> </title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="label" runat="server">New Task</asp:Label>
<asp:TextBox ID="textbox1" runat="server" placeHolder="Type
new task summary here, and click add" Width="353px">
</asp:TextBox>
<asp:Button ID="button1" runat="server" OnClick="click_add"
Text="Add" style="margin-left: 54px" Width="67px" />
<br />
</div>
<asp:GridView ID="grdStatus" runat="server"
OnRowCommand="grdStatus_RowCommand" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Done?">
<ItemTemplate>
<asp:CheckBox ID="checkbx" runat="server"
Checked='<%#Eval("Done") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="label12" runat="server"
Checked='<%#Container.DataItemIndex+1 %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Summary">
<ItemTemplate>
<asp:Label ID="label3" runat="server"
Checked='<%#Eval("Summary") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Created On">
<ItemTemplate>
<asp:Label ID="label4" runat="server"
Checked='<%#Eval("Date")%>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="dltButton" runat="server"
ImageUrl="~/images/delete.png"
CommandName="DeleteTask" Text="Delete" Width="30px"
Height="30px" CommandArgument="<%#
Container.DataItemIndex%>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
</body>
</html>
The c# code is this
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string connectionString =
WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
string selectSQL = "SELECT * FROM Table";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds, "Table");
grdStatus.DataSource = ds;
grdStatus.DataBind();
}
}
protected void click_add(object sender, EventArgs e)
{
string connectionString =
WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("INSERT INTO
Table(ID,Summary) values ('" +
convert.ToInt32(cmd.Parameters["label2"].Value.ToString())
+ "'" + textbox1.Text + "'" DateTime.Text+ "'", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
protected void grdStatus_RowCommand(object sender, EventArgs e)
{
if(e.CommandName == "DeleteTask")
{
string connectionString =
WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
con.Open();
string query = "delete from Table where id=" +
e.CommandArgument + "'";
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();
fillgrid();
}
}
}
Please find attached the entire code for the .aspx file:
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="LeftContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" Runat="Server">
<asp:SqlDataSource ID="DSProduct" runat="server"> </asp:SqlDataSource>
<asp:SqlDataSource ID="DSSize" runat="server" > </asp:SqlDataSource>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="DSProduct"
onitemcommand="Repeater1_ItemCommand" >
<ItemTemplate>
<br />
<asp:Image ID="Image1" runat="server"
ImageUrl='<%#Eval("image2","~/Image/{0}") %>'
Height="230" Width="230"
CssClass="largeimage" />
<h3 style="color: #FFFFFF; font-weight: bold; ">
<asp:Label ID="LName" runat="server" Text='<%# Eval("product_name")%>'>
</asp:Label>
<asp:Label ID="LPrice" style="text-decoration: line-through;" runat="server"
Text='<% # Convert.ToDecimal(Eval("price")).ToString("£#,##0.00") %>' Font-Size="Small" ForeColor = "Blue" >
</asp:Label>
<asp:Label ID="Label4" runat="server" Text=" £ " ForeColor="Red" BackColor="White">
</asp:Label>
<asp:Label ID="LPrice_disc" runat="server" Text='<%# Convert.ToDecimal(Eval("discount_price")).ToString("#,##0.00") %>'
BackColor="White" ForeColor = "Red">
</asp:Label>
<asp:Label ID="LID" runat="server" Text='<%# Eval("product_id") %>' Visible="False">
</asp:Label> </h4>
<asp:SqlDataSource ID="DSColour" runat="server"
ConnectionString="<%$ ConnectionStrings:XXX %>"
ProviderName="<%$ ConnectionStrings:XXX.ProviderName %>"
SelectCommand="select colour_id, colour_name from colour">
</asp:SqlDataSource>
<asp:DropDownList ID="DDListColour" runat="server"
DataSourceID="DSColour" DataTextField="colour_name"
DataValueField="colour_id"
AppendDataBoundItems="true"
OnSelectedIndexChanged="colour_SelectedIndexChanged"
AutoPostBack="True" >
</asp:DropDownList>
<asp:SqlDataSource ID="DSSize" runat="server"
ConnectionString="<%$ ConnectionStrings:XXX %>"
ProviderName="<%$ ConnectionStrings:XXX.ProviderName %>"
SelectCommand="select size_id, size_name from size_t">
</asp:SqlDataSource>
<asp:DropDownList ID="DropDownListSize" runat="server"
DataSourceID="DSSize" DataTextField="size_name"
DataValueField="size_id" AutoPostBack="True" >
</asp:DropDownList>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("product_id") %>' Visible="True">
</asp:Label>
<h5 style="color: #000000; font-weight: normal;" >
<asp:Label ID="Ldesc" runat="server" Text='<%# Eval("product_description")%>' Width="500" Font-Size="Medium" Font-Bold="True">
</asp:Label></h5>
<asp:ImageButton ID="Button1" runat="server" CssClass="addcart" ImageUrl="~/Image/btn_buy.gif" />
</ItemTemplate>
</asp:Repeater>
</asp:Content>
Please find below the code for the code behind file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class Product : System.Web.UI.Page
{
private string DataValueField;
private string Colour;
protected void Page_Load(object sender, EventArgs e)
{
String pid = Request.QueryString["pid"];
DSProduct.ConnectionString = "Data Source=X;Persist Security Info=True;User ID=Y;Password=Z";
DSProduct.ProviderName = "System.Data.OracleClient";
DSProduct.SelectCommand = "SELECT * FROM Product WHERE product_id= '" + pid + "'";
}
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
string url = HttpContext.Current.Request.Url.AbsoluteUri;
Boolean flag_found;
int i;
DataTable LocalCart = new DataTable();
LocalCart.Columns.Add("Colour",typeof(String));
DataRow dr;
Session["curURL"] = url;
if (Session["username"] == null) Response.Redirect("login.aspx");
LocalCart = (DataTable)Session["cart"];
int LocalCartItemCount = (int)Session["CartItemCount"];
Decimal LocalCartAmount = (Decimal)Session["CartAmount"];
flag_found = false;
for (i = 0; i < LocalCart.Rows.Count; i++)
{
if (LocalCart.Rows[i]["ID"].Equals(((Label)e.Item.FindControl("LID")).Text.ToString()))
{
LocalCart.Rows[i]["Quantity"] = Convert.ToInt32(LocalCart.Rows[i]["Quantity"]) + 1;
LocalCart.Rows[i]["Subtotal"] = Convert.ToInt32(LocalCart.Rows[i]["Quantity"]) * Convert.ToDecimal(LocalCart.Rows[i]["Price"]);
flag_found = true;
break;
}
}
if (!flag_found)
{
dr = LocalCart.NewRow();
dr["ID"] = ((Label)e.Item.FindControl("LID")).Text.ToString();
dr["Name"] = ((Label)e.Item.FindControl("LName")).Text.ToString();
dr["Price"] = Convert.ToDecimal(((Label)e.Item.FindControl("LPrice_disc")).Text.ToString());
dr["Quantity"] = 1;
dr["Subtotal"] = Convert.ToDecimal(dr["Price"]);
dr["Colour"] = ((DropDownList)e.Item.FindControl("DDListColour")).SelectedValue;
LocalCart.Rows.Add(dr);
}
LocalCartItemCount++;
LocalCartAmount += Convert.ToDecimal(((Label)e.Item.FindControl("LPrice_disc")).Text.ToString());
Session["Cart"] = LocalCart;
Session["CartAmount"] = LocalCartAmount;
Session["CartItemCount"] = LocalCartItemCount;
Response.Redirect("CartDisp.aspx");
}
}
Like I said I am having the following error (related to the 'Colour' column that is not recognised for some reason):
Exception Details: System.ArgumentException: Column 'Colour' does not belong to table .
Source Error:
Line 62: dr["Quantity"] = 1;
Line 63: dr["Subtotal"] = Convert.ToDecimal(dr["Price"]);
Line 64: dr["Colour"] = ((DropDownList)e.Item.FindControl("DDListColour")).SelectedValue;
Line 65: LocalCart.Rows.Add(dr);
Thank you in advance.
S
I have found a solution, I have followed the hint given by Rick. However this causes another issue: that when you add a column below the if statement, the second time the code runs you will receive an error message because the column already exists. I have found a way around, that you can find below.
if (!flag_found)
{
{ // This checks if the columns are there already
if (LocalCart.Columns["Colour"] != null && LocalCart.Columns["Size"] != null )
{
dr = LocalCart.NewRow();
dr["ID"] = ((Label)e.Item.FindControl("LID")).Text.ToString();
dr["Name"] = ((Label)e.Item.FindControl("LName")).Text.ToString();
dr["Price"] = Convert.ToDecimal(((Label)e.Item.FindControl("LPrice_disc")).Text.ToString());
dr["Quantity"] = 1;
dr["Subtotal"] = Convert.ToDecimal(dr["Price"]);
dr["Colour"] = ((DropDownList)e.Item.FindControl("DDListColour")).SelectedValue;
dr["Size"] = ((DropDownList)e.Item.FindControl("DDListSize")).SelectedValue;
LocalCart.Rows.Add(dr);
}
else
{ // This generates the columns if they are not there already
LocalCart.Columns.Add("Colour", typeof(String));
LocalCart.Columns.Add("Size", typeof(String));
dr = LocalCart.NewRow();
dr["ID"] = ((Label)e.Item.FindControl("LID")).Text.ToString();
dr["Name"] = ((Label)e.Item.FindControl("LName")).Text.ToString();
dr["Price"] = Convert.ToDecimal(((Label)e.Item.FindControl("LPrice_disc")).Text.ToString());
dr["Quantity"] = 1;
dr["Subtotal"] = Convert.ToDecimal(dr["Price"]);
dr["Colour"] = ((DropDownList)e.Item.FindControl("DDListColour")).SelectedValue;
dr["Size"] = ((DropDownList)e.Item.FindControl("DDListSize")).SelectedValue;
LocalCart.Rows.Add(dr);
}
}
}
Working on a basic C# web app here and I can't seem to get the GridView to show. I can see that its passing the code through because it changes my image from one to another but for some reason the Gridview doesn't show up. Using the button for the postback and my dropdown box has the variable for my stored procedure. I'm new to C# web apps (Vb Win app guy here) so I need a little guidance please.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, System.EventArgs e)
{
//This is where my postback begins...
if (IsPostBack)
{
string Quote = null;
System.Data.SqlClient.SqlConnection myDatabaseConnection = null;
System.Data.SqlClient.SqlCommand myCommand = null;
System.Data.SqlClient.SqlDataReader myReader = null;
// Validate the SP
Page.Validate();
if (Page.IsValid)
{
Quote = DropDownList1.Text.ToString();
try
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Data1"].ConnectionString;
myDatabaseConnection = new System.Data.SqlClient.SqlConnection(connectionString);
myCommand = new System.Data.SqlClient.SqlCommand();
//Set up to use my stored procedure:
myCommand.CommandType = System.Data.CommandType.StoredProcedure;
myCommand.Connection = myDatabaseConnection;
myCommand.CommandText = "EditDataPage";
myCommand.Parameters.AddWithValue("#QuoteNumber", Quote);
//Use an SqlDataReader to execute the stored procedure and
//get the results into the GridView:
myDatabaseConnection.Open();
myReader = myCommand.ExecuteReader();
GridView1.DataSource = myReader;
GridView1.DataBind();
myDatabaseConnection.Close();
myDatabaseConnection.Dispose();
GridView1.Visible = true;
Image1.Visible = false;
Image2.Visible = true;
}
catch (System.Data.SqlClient.SqlException exception)
{
ErrorLabel.Visible = true;
}
catch (Exception exception)
{
ErrorLabel.Visible = true;
//Do cleanup tasks here:
}
finally
{
myCommand = null;
if ((myReader != null) && !myReader.IsClosed)
{
myReader.Close();
}
myReader = null;
if ((myDatabaseConnection != null) && myDatabaseConnection.State == System.Data.ConnectionState.Open)
{
myDatabaseConnection.Close();
myDatabaseConnection.Dispose();
}
myDatabaseConnection = null;
}
}
}
}
}
Heres my aspx code:
Edit Data
Use the controls to move within the dataset, then edit and save what you need
for your reports.
<table class="yui-d0f">
</table>
<table class="yui-main">
<tr>
<td>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Data1 %>"
SelectCommand="EditDataPage" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:FormParameter FormField="DropDownList1" Name="QuoteNumber" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<table class="style1">
<tr>
<td align="center">
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="DropDownList"
DataTextField="QuoteNumber" DataValueField="QuoteNumber" Height="23px"
Width="188px">
</asp:DropDownList>
<asp:SqlDataSource ID="DropDownList" runat="server"
ConnectionString="<%$ ConnectionStrings:Data1 %>"
SelectCommand="SELECT QuoteNumber FROM SF1411 GROUP BY QuoteNumber">
</asp:SqlDataSource>
</td>
<td>
<table class="style1">
<tr>
<td class="style2">
<asp:Button ID="ListAllButton" runat="server" Height="32px" Text="Show Data"
Width="111px" PostBackUrl="~/EditData.aspx" />
</td>
<td>
<asp:Image ID="Image1" runat="server"
ImageUrl="~/_assets/img/lock-disabled-icon.png" />
<asp:Image ID="Image2" runat="server" ImageUrl="~/_assets/img/lock-icon.png"
Visible="False" />
</td>
</tr>
</table>
</td>
</tr>
</table>
<asp:Label ID="ErrorLabel" runat="server" Font-Underline="True"
ForeColor="Maroon" Text="Error in Processing, try again later." Visible="False"></asp:Label>
</td>
</tr>
</table>
<asp:GridView ID="GridView1" runat="server" CssClass="styled"
AutoGenerateColumns="False">
</asp:GridView>
I'm not 100% sure, but the fact that you've got AutoGenerateColumns="false" on your GridView yet no columns defined looks a bit suspicious. I guess as a quick test you could change this attribute to true and see what happens.
If you do indeed want to specify the columns yourself (which in my experience is the norm), then you need to specify them, like this for example:
<asp:GridView ...>
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:TemplateField>
<asp:Label Text='<%# Eval("Surname") %>' runat="server" />
</asp:TemplateField>
</Columns>
</asp:GridView>
See MSDN for more details.