I'm having a project to create a website that connects my database to perform different functionalities. When I create the web form and connects it with the database, and when i click the button it's supposed that all the products will appear but it doesn't happen.
This is the SQL procedure:
CREATE PROC reviewOrders
AS
BEGIN
SELECT *
FROM Orders
END
And this is the c# code
protected void reviewOrders(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString();
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("reviewOrders", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
and the HTML code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ReviewOrders.aspx.cs"
Inherits="GUCommerce.ReviewOrders" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="viewOrders" runat="server" OnClick ="reviewOrders" Height="45px"
Text="view orders" Width="148px" />
</div>
<p style="height: 121px">
</p>
<asp:Panel ID="x" Visible ="false" runat="server" Height="338px">
<asp:Table ID="orders" CellPadding ="4" runat="server" Height="67px" Width="316px">
</asp:Table>
</asp:Panel>
</form>
</body>
</html>
Can one please tell me what is missing?
Thanks is advance!
I would recommend using ASP Gridview instead of ASP Table. Gridviews (<asp:GridView>) are used to present data in tables. They actually get rendered as html tables. Here is how to build one using your code:
<asp:Panel ID="x" Visible="false" runat="server" Height="338px">
<%--<asp:Table ID="orders" CellPadding="4" runat="server" Height="67px" Width="316px"></asp:Table>--%>
<asp:GridView ID="gvOrders" CellPadding="4" runat="server" Height="67px" Width="316px"></asp:GridView>
</asp:Panel>
Now, in the code-behind there are a couple changes. A DataTable can be used to store the results of your query and then you can bind a DataTable to a GridView. To do this, you need a SqlDataAdapter which is shown below.
protected void reviewOrders(object sender, EventArgs e)
{
// data table variable outside of sql block
// you could also move the sql code to another method that returns a datatable
DataTable dt = null;
string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString();
using (SqlConnection conn = new SqlConnection(connStr))
{
SqlCommand cmd = new SqlCommand("reviewOrders", conn);
cmd.CommandType = CommandType.StoredProcedure;
using (cmd)
{
conn.Open();
// Use SQL Data Adapter instead of Execute Non Query
using (SqlDataAdapter _Adapter = new SqlDataAdapter(cmd))
{
// Fill DataTable with results of query
dt = new DataTable();
_Adapter.Fill(dt);
}
}
}
//
gvOrders.DataSource = dt;
gvOrders.DataBind();
}
Note: I use using(SqlConnection) and using(cmd) to handle closing the connection and command for me. Give this a shot.
Related
Basically what the task is that you search someone's name in the textbox, click search, the users with that name will populate the dropdown list.
SQL Server: this is the query I am try to add to the search button on my page:
SELECT Users.Forename + ' ' + Users.Surname AS [Name], Users.ID
From Users
Order by [Name]
Aspx side:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Page1.aspx.cs" Inherits="SearchRecords.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<p> Search User </p>
<p> Filter Users: <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
<asp:Button ID="SearchButton1" runat="server" Text="Search" OnClick="BtnSearch_Click" />
<br />
<br />
Select a user:
<asp:DropDownList ID="DDLSelectUser1" runat="server"> </asp:DropDownList>
<asp:Label ID="lblUserCount" runat="server" Text=""></asp:Label>
<br />
<div class="DataGrid">
<asp:GridView ID="DataGrid1" runat="server" ShowHeaderWhenEmpty="false" EmptyDataText="No data found!">
</asp:GridView>
</div>
</p>
<p> Link to page 1 </p>
</div>
</form>
</body>
</html>
C# side: I've got this already (this is me attempting to fetch data from the Database and bind the list of names to the dropdown list):
private void LoadIntoDropdown()
{
using (SqlConnection connection = new SqlConnection("Data Source=DEV-WEB;Initial Catalog=Isabelle;Integrated Security=True"))
{
connection.Open();
string sqlQuery = "SELECT Users.Forename + ' ' + Users.Surname AS [Name], Users.ID From Users WHERE Forename like '%'+#Forename+'%'";
using (SqlCommand cmd = new SqlCommand(sqlQuery, connection))
{
cmd.Parameters.AddWithValue("Forename", TextBox1.Text);
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
adapter.Fill(dt);
DDLSelectUser1.DataTextField = "[Name]";
DDLSelectUser1.DataValueField = "Users.ID";
DDLSelectUser1.DataSource = dt;
DDLSelectUser1.DataBind();
}
}
connection.Close();
}
}
It's never working, this is what I get:
"DataBinding: 'System.Data.DataRowView' does not contain a property with the name '[Name]'."
And I don't understand why? I combined two columns from the database, the Forename and Surname columns, together and called it [Name], so it does exist.
I can't seem to find online the right answer to my question as they all are 'select from the dropdown list to fill the textbox' I want the other way around, if it's possible!
The alias [Name] in your query becomes just Name once the database returns the resultset to the client (in this case, your program). So, when you reference that column in your code, you should do it as Name instead of [Name]
DDLSelectUser1.DataTextField = "Name";
Square bracket names and aliases are used in SQL Server queries both to specify that you want the name/alias to be exactly as written (including "invalid" characters for names like spaces e.g. [First Name]) and to differentiate such names/aliases from keywords (althought using keywords as field names is not recommended).
You can find more information in this SO question and in this Microsoft Docs' question
well i'm trying to show a grid of records that i have in my database but whenever i click on the button nothing happens
sorry for asking such a really dumb question but i'm total noob here and i tried
to find any solution but i can't find any
HTML:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
enter something</div>
<p>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</p>
<p>
<input id="Button1" type="button" value="Search" runat="server" onclick="Myp" /></p>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
test<input id="Hidden1" type="hidden" /></form>
<p>
</p>
</body>
</html>
C#
protected void Myp(object sender, System.EventArgs e)
{
//Get the button that raised the event
//Button btn = (Button)sender;
string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString();
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
SqlCommand cmd = new SqlCommand("SearchByName", conn);
cmd.CommandType = CommandType.StoredProcedure;
string name = TextBox2.Text;
cmd.Parameters.Add(new SqlParameter("#name", name));
GridView1.EmptyDataText = "No Records Found";
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// SqlDataAdapter adapter = cmd.ExecuteReader();
//adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
GridView1.Visible = true;
}
Try using the OnClick event as opposed to onclick, which is going to likely target a Javascript function (as opposed to your server-side Myp method):
<input id="Button1" type="button" value="Search" runat="server" OnClick="Myp" />
Additionally, if your method still is not being called, you should try looking at the Events properties for your Button1 button to ensure that your OnClick event handler is configured properly and points to the Myp method.
I am trying to implement a search textbox with the Ajax Control Toolkit AutoCompleteExtender. The result should be a list of names matching the entered text however what gets displayed is the page source HTML, character by character, creating an extremely long list of single letters.
I have found and tried several samples but cannot get this to work. I am certain the database connection is valid and the SQL query when executed directly in MSSMS, returns the expected result. The AjaxControlToolkit is installed and works on other pages in the solution.
This issue was asked before ("Ajax Control Toolkit AutoCompleteExtender displays html source character by character of the current page as autocomplete suggestion list"). However for reasons of simplicity and maintainability I do not want to implement a WebService as this poster did.
acex.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AutoCompleteExtender - Last Names</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:TextBox ID="txbxLastName" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
TargetControlID="txbxLastName"
MinimumPrefixLength="2"
EnableCaching="true"
CompletionSetCount="1"
CompletionInterval="1000"
ServiceMethod="GetLastNames">
</asp:AutoCompleteExtender>
</div>
</form>
</body>
</html>
acex.aspx.cs
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace MCA
{
public partial class acex : System.Web.UI.Page
{
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetLastNames(string prefixText)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString());
SqlCommand cmd = new SqlCommand("SELECT [Last_Name] FROM [Entity_Person] WHERE [Last_Name] LIKE #Name+'%'", conn);
cmd.Parameters.AddWithValue("#Name", prefixText);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
conn.Open();
da.Fill(dt);
List<string> LastNames = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
LastNames.Add(dt.Rows[i][0].ToString());
}
return LastNames;
}
}
}
Very new to writing code, please be gentle...
I have a database that keeps track of images that I post online, who was in the image, date taken, etc. I then have an ASPX page that based on the ID I pass in brings me back a gridview of the image, location online etc. This helps me keep track of how many places I may have used a single image.
Everything works great, but I get one row per image URL in my grid view. I want to have the image appear once on my page, then one of the cells list out the URLs.
Here is my C#:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["db2257conn"].ConnectionString;
String strQuery = "select mFirstName, mDOB, cURL, fID, fURL, cDate from vwAllModelContent where " + Context.Request.QueryString["mID"] + " IN(mID1, mID2, mID3) and cactive = 1 order by cDate, fType, fName, cURL";
SqlCommand cmd = new SqlCommand(strQuery);
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView2.DataSource = dt;
GridView2.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
{
}
Here is the ASPX:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="modelcontent2.aspx.cs" Inherits="modeldatabase.modelcontent2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form2" runat="server">
<div>
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false" Font-Names="Arial" OnSelectedIndexChanged="GridView2_SelectedIndexChanged" >
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="fURL" DataTextField="furl" DataTextFormatString="<img src='{0}' width='200' border='0' />" Target="_blank" HeaderText="Image Link" Text="Image Link" />
<asp:BoundField DataField ="cDate" HeaderText ="Shoot Date" />
<asp:BoundField DataField ="mFirstName" HeaderText="Model First Name" />
<asp:BoundField DataField="mDOB" HeaderText="DOB" />
<asp:BoundField DataField="fID" HeaderText="File ID" />
<asp:HyperLinkField DataNavigateUrlFields="cURL" DataTextField="cURL" HeaderText ="URL" Target="_blank" Text="URL" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
And my rep is too new to post an image of the results, but suffice it to say I see multiple rows for the same image, one for each URL.
I'd like to see the image and other data as a single row, then in the URL column have all of the URLs that the image appears at.
Maybe not very performant but try a subselect
String strQuery = "select mFirstName, mDOB, (SELECT cURL + ',' FROM vwAllModelContent where " + Context.Request.QueryString["mID"] + " IN (mID1, mID2, mID3)) , fID, fURL, cDate from vwAllModelContent where " + Context.Request.QueryString["mID"] + " IN(mID1, mID2, mID3) and cactive = 1 order by cDate, fType, fName, cURL LIMIT 1";
I'm not sure if it works, didn't use sql for a long time
Question: Why do you have three columns for IDs? (mID1, mID2, mID3)
What you are defining is called a "1 to many" relationship.
Gridview's are designed to show multiple rows tabular type data. If you want to display 1 image and multiple rows of associated data there are several ways of doing this.
Typically this would require 2 database calls:
one that returns the image source link
one that returns the rows of associated data.
Since the first call is really only providing an img src you don't really need a databound control for that, just obtain the string and drop it into an <asp:Image /> control or an <asp:ImageButton /> (if you prefer the image to be a link) and set the ImageUrl property
The second call is returning multiple rows of data, use your existing Gridview, you only need to remove the image reference.
Im using Microsoft Visual Studio 2012 as platform and i have created Web Forms Project
i have created data base file "SimpleDB.mdf" inside his "Table" folder i added new table called "Table" which has two columns - id and Name(string).What im trying is to insert string data into Name column of this table while calling server side function from javascript function.
This is the aspx.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.Services;
namespace ProjectWWW
{
public partial class WebForm1 : System.Web.UI.Page
{
[WebMethod]
public static string InsertData(string ID){
string source = "Data Source=(LocalDB)\v11.0;Integrated Security=True;Connect Timeout=30";
SqlConnection con = new SqlConnection(source);
{
SqlCommand cmd = new SqlCommand("Insert into Table(Name) values('" + ID + "')", con);
{
con.Open();
cmd.ExecuteNonQuery();
return "True";
}
}
}
}
and this is the aspx code
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="ProjectWWW.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script>
function CallMethod() {
PageMethods.InsertData("hello", CallSuccess, CallError);
}
function CallSuccess(res) {
alert(res);
}
function CallError() {
alert('Error');
}
</script>
</head>
<body>
<header>
</header>
<div class="table" id="div1" > </div>
<form id="Form1" runat="server">
<asp:Button id="b1" Text="Submit" runat="server" onclientclick="CallMethod();return false;"/>
<asp:ScriptManager enablepagemethods="true" id="ScriptManager1" runat="server"></asp:ScriptManager>
</form>
</body>
</html>
So basically im expecting when the button submit is clicked the Table Column "Name" will be filled with "Hello" but nothing happens and the column stays empty(NULL)
Table is reserved word in T-SQL so i would suggest you to use [] square brackets to enclose the Table.
Try This:
SqlCommand cmd = new SqlCommand("Insert into [Table](Name)
values('" + ID + "')", con);
Suggestion: Your query is open to sql injection attacks.I would suggest you to use Parameterised Queries to avoid them.
Try This:
using(SqlConnection con = new SqlConnection(source))
{
using(SqlCommand cmd = new SqlCommand("Insert into [Table](Name)
values(#Name)", con))
{
con.Open();
cmd.Parameters.AddWithValue("#Name",ID);
cmd.ExecuteNonQuery();
return "True";
}
}