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);
Related
Heres the dropdownlist and datalist code
<div>
Sort by Category:
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>All</asp:ListItem>
<asp:ListItem>Decoration</asp:ListItem>
<asp:ListItem>Catering</asp:ListItem>
<asp:ListItem>Entertainment</asp:ListItem>
<asp:ListItem>Sound</asp:ListItem>
<asp:ListItem>Others</asp:ListItem>
</asp:DropDownList>
<asp:DataList ID="DataList1" runat="server"
GridLines="Both" RepeatColumns="4" RepeatDirection="Horizontal"
Width="1000px" DataSourceID="SqlDataSource1" >
<ItemTemplate>
<table class="nav-justified">
<tr>
<td class="text-center">
<strong>
<asp:Label ID="Label1" runat="server"
Text='<%# Eval("serName") %>'></asp:Label>
</strong>
</td>
</tr>
<tr>
<td>
<asp:Image ID="Image1" runat="server" Height="179px"
ImageUrl='<%# Eval("serImg") %>' Width="191px"/>
</td>
</tr>
<tr>
<td>
<strong>
<asp:Label ID="Label2" runat="server" Text="Rs"></asp:Label>
<asp:Label ID="Label3" runat="server"
Text='<%# Eval("sprice") %>'>
</asp:Label>
</strong>
</td>
</tr>
<tr>
<td class="text-center">
<asp:Button ID="Button1" runat="server" Text="Details" />
</td>
</tr>
</table>
<br />
</ItemTemplate>
</asp:DataList>
</div>
Here is the .cs code. Its purpose is to filter the data in the list according to the selected category in the dropdown list
protected void Page_Load(object sender, EventArgs e)
{
String conString = ConfigurationManager.ConnectionStrings["regcon"].ConnectionString;
string query = "select * from addService where serCategory=#cat";
SqlCommand cmd = new SqlCommand(query);
cmd.Parameters.AddWithValue("#cat", DropDownList1.SelectedItem.Value);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
DataList1.DataSource = ds;
DataList1.DataBind();
}
}
}
}
I get the error "Both DataSource and DataSourceID are defined on 'DataList1'. Remove one definition." when i run it.Removing the Datalist1 or DataSourceID would give an error.How do i fix this?
The problem is, on the datalist you have a datasource
DataSourceID="SqlDataSource1"
Then you also apply a data source in the code behind
DataList1.DataSource = ds;
You can't do both. You could remove the existing one in code then apply a new one if you want.
I have an issue trying to display image in my DataList from the database and have access to the database that I'm pulling my images from. But when I run the WebForm the image does not appear, what is wrong in my codes?
<asp:DataList ID="DataList1" runat="server" DataKeyField="dishID" DataSourceID="SqlDataSource1" BorderStyle="Solid" GridLines="Both" RepeatColumns="4" RepeatDirection="Horizontal" Width="1259px" >
<ItemTemplate>
<table class="auto-style1">
<tr><td>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "FoodPictures/" + Eval("dishImage") %>' />
This is how I'm retrieving from the database:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(_connStr);
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from Dish";
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
conn.Close();
DataList1.DataSource = dt;
DataList1.DataBind();
conn.Close();
}
I think Your Page do not get image on proper path....
use
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "../FoodPictures/" + Eval("dishImage") %>' />
Or
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "~/FoodPictures/" + Eval("dishImage") %>' />
Try this..
Assuming if dishImage is a name like imagename.jpg stored in database then try Convert.ToString(Eval("dishImage")) like:
<asp:Image ID="Image1" ImageUrl='<% # "~/FoodPictures/" + Convert.ToString(Eval("dishImage")) %>' runat="server" />
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.
.aspx file code
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div style="background-color:lightgray;font-family:'Comic Sans MS' ">
<br />
<h2 style="text-align:center;"> CONTACT <b><span style="color:red">L</span>EA<span style="color:darkgreen">P</span></b> DRIVING SCHOOL</h2>
<br />
<fieldset style="align-content:center; color:lightgray;text-align:center ">
<br /> <br />
<asp:Label ID="Label2" runat="server" Text="Name" ForeColor="Black"></asp:Label><br />
<asp:TextBox ID="TextBox1" runat="server" size="25" > </asp:TextBox> <%--<asp:RequiredFieldValidator
ID="rfvName" runat="server" ErrorMessage="Please enter Name"
ControlToValidate="TextBox1" Display="Dynamic" ForeColor="#FF3300"
SetFocusOnError="True"></asp:RequiredFieldValidator> --%> <br /> <br />
<asp:Label ID="Label3" runat="server" Text="mobile number" ForeColor="Black"></asp:Label> <br />
<asp:TextBox ID="TextBox2" runat="server" size="25" ForeColor="Black"></asp:TextBox> <%-- <asp:RequiredFieldValidator
ID="RequiredFieldValidator2" runat="server" ErrorMessage="Please enter Number"
ControlToValidate="TextBox2" Display="Dynamic" ForeColor="#FF3300"
SetFocusOnError="True"></asp:RequiredFieldValidator> --%> <br /> <br />
<asp:Label ID="Label4" runat="server" Text="Email" ForeColor="Black"></asp:Label> <br />
<asp:TextBox ID="TextBox3" runat="server" size="25" ></asp:TextBox> <%--<asp:RequiredFieldValidator ID="rfvEmailId" runat="server"
ControlToValidate="TextBox3" Display="Dynamic"
ErrorMessage="Please enter Email Id" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="rgeEmailId" runat="server"
ControlToValidate="TextBox3" Display="Dynamic"
ErrorMessage="Please enter valid email id format" ForeColor="Red"
SetFocusOnError="True"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator> --%> <br /> <br />
<asp:Label ID="Label5" runat="server" Text="City" ForeColor="Black"></asp:Label> <br />
<asp:TextBox ID="TextBox4" runat="server" size="25" ></asp:TextBox> <br /> <br />
<asp:Label ID="Label6" runat="server" Text="Message" ForeColor="Black"></asp:Label> <br />
<asp:TextBox id="TextArea1" TextMode="multiline" Columns="27" Rows="8" runat="server" /> <br /> <br />
<asp:Button ID="Button1" runat="server" Text="Submit" Font-Bold="true" BackColor="Green" Width="83px" height="37px" OnClick="Button1_Click" />      
<asp:Button ID="Button2" runat="server" Text="Reset" Font-Bold="true" BackColor="red" Width="83px" height="37px"/>
<br /> <br />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</fieldset>
<br />
<br />
</div>
</asp:Content>
.css file code
protected void Button1_Click(object sender, EventArgs e)
{
// string connstring=ConfigurationManager.ConnectionStrings["yourconnstringInWebConfig"].ConnectionString;
// SqlConnection con = new SqlConnection();
// SqlConnection con = new SqlConnection();
// con.ConnectionString = "Data Source=ADMIN;Initial Catalog=contact;Integrated Security=True";
string insertSQL="INSERT INTO dbo.contct(" ;
insertSQL += "name,number,email,city,msg)";
insertSQL += "VALUES ('";
insertSQL += TextBox1.Text + "','";
insertSQL += TextBox2.Text + "','";
insertSQL += TextBox3.Text + "','";
insertSQL += TextBox4.Text + "','";
insertSQL += TextArea1.Text + "','";
SqlConnection con = new SqlConnection("Data Source=ADMIN;Initial Catalog=contact;Integrated Security=True");
SqlCommand cmd = new SqlCommand(insertSQL,con);
int added = 0;
try {
con.Open();
added = cmd.ExecuteNonQuery();
Label1.Text = added.ToString() + "successfuly your information is submitted thank you!!";
}
catch (Exception er)
{
Label1.Text = "error while inserting record";
Label1.Text = er.Message;
}
finally
{
con.Close();
}
}
}``
these are two file code form and sql query to insert value into form when user submits button it should add value to the table i created in sql database but no data is going there no value is being submitted i have tried no. of times but its not working plz help me out in this
Yous insert query sytax was incorrect hence no data was inserting. You was missing the closing bracket ) from VALUES(), Currently your query is vulnerab to sql injection. I have parameterized your query and made changes to your code to reflect this. It is also recommended to make use of the using block to close and dispose the connection correctly.
string myQuery = "INSERT INTO dbo.contct(name,number,email,city,msg) VALUES(#name, #number, #email, #city, #msg)";
using (var connection = new SqlConnection("YourConnectionString"))
{
using (var cmd = new SqlCommand(myQuery, connection))
{
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = TextBox1.Text;
cmd.Parameters.Add("#number", SqlDbType.NVarChar).Value = TextBox2.Text;
cmd.Parameters.Add("#email", SqlDbType.NVarChar).Value = TextBox3.Text;
cmd.Parameters.Add("#city", SqlDbType.NVarChar).Value = TextBox4.Text;
cmd.Parameters.Add("#msg", SqlDbType.NVarChar).Value = TextArea1.Text;
connection.Open();
cmd.ExecuteNonQuery();
}
} //Connection closed and disposed autmatically here
Read up on Sql injection here
You forgot to close VALUES()
string insertSQL="INSERT INTO dbo.contct(" ;
insertSQL += "name,number,email,city,msg)";
insertSQL += "VALUES ('";
insertSQL += TextBox1.Text + "','";
insertSQL += TextBox2.Text + "','";
insertSQL += TextBox3.Text + "','";
insertSQL += TextBox4.Text + "','";
insertSQL += TextArea1.Text + "')";
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