showing a grid after clicking on a button - c#

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.

Related

the button is not doing its supposed function

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.

How to enable the dropdown list on a specific radio button

I am trying to enable the dropdown list when the user select the radio button with a id =9, for some reason the jquery function is not working
For debugging purpose, i've tried to alert the selected id but it's null
Any thoughs?
C# code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string constr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "SELECT * FROM case_cat_lv1";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
rblFruits.DataSource = cmd.ExecuteReader();
rblFruits.DataTextField = "category_name";
rblFruits.DataValueField = "id";
rblFruits.DataBind();
con.Close();
}
}
}
}
ASP.NET .aspx
<form id="form1" runat="server">
<div>
<asp:RadioButtonList ID="rblFruits" runat="server" OnCheckedChanged="air_CheckedChanged" class="radio">
</asp:RadioButtonList>
<br />
<asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="Submit" />
<asp:DropDownList ID="airlist" runat="server" Font-Size="20px" class="dropdown">
<asp:ListItem>Air India</asp:ListItem>
<asp:ListItem>Kingfisher</asp:ListItem>
<asp:ListItem>Jet Airways</asp:ListItem>
<asp:ListItem>Spice Jet</asp:ListItem>
</asp:DropDownList>
</div>
<script>
$(document).ready(function () {
$('.dropdown').attr("disabled", true);
$('#rblFruits').change(function () {
alert($(this).val());
if ($(this).val() == '9') {
$('.dropdown').attr("disabled", false);
}
else {
$('.dropdown').attr("disabled", true);
}
//alert($(this).val());
});
});</script>
</form>
Try $(this).find(":checked").val(); instead of $(this).val(). And if you want id of selected radio button then $(this).find(":checked").attr("id").
To enable dropdown list you can remove attribute disabled. It should work.
$('.dropdown').removeAttr("disabled");
For disabling your code will work fine.
$('.dropdown').attr("disabled", true);
A few of things to consider. ASP.net webforms can mangle ids, RadioButtonList is not an HTML entity and is rendered as radio buttons with their own ids and values, finally you also have OnCheckedChanged="air_CheckedChanged" as a server side event handler which could be causing you problems.
With these kinds of issues with .net WebForms, always check the rendered HTML to see if it is what you were expecting.
Here's how I'd do it:
<form id="form1" runat="server">
<div>
<!-- I've taken out the server side event handler -->
<asp:RadioButtonList ID="rblFruits" runat="server" class="radio">
</asp:RadioButtonList>
<br />
<asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="Submit" />
<asp:DropDownList ID="airlist" runat="server" Font-Size="20px" class="dropdown">
<asp:ListItem>Air India</asp:ListItem>
<asp:ListItem>Kingfisher</asp:ListItem>
<asp:ListItem>Jet Airways</asp:ListItem>
<asp:ListItem>Spice Jet</asp:ListItem>
</asp:DropDownList>
</div>
<script>
$(document).ready(function () {
$('.dropdown').attr("disabled", true);
/*#rblFruits will be a container, not actual radio buttons*/
/*Keeping in mind name mangling, get the actual client ID.
Note that if you're putting thing in an external js file,
you'll need to come up with another plan*/
$('#<%=rblFruits.ClientID%> input[type=radio]').change(function () {
alert($(this).val());
$('.dropdown').prop("disabled", $(this.val() !== '9'));
});
});</script>
</form>
See also: http://api.jquery.com/prop/

While inserting record into SQL Server database form asp.net web form its inserting twice

I am inserting values into a web form and submitting the web form. The record gets inserted twice in my SQL Server 2014 database. My web form code and code behind logic are below.
I don't know why the record is being inserted twice into the database.
Web form code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="register.aspx.cs" Inherits="register" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Social Login Form Flat Responsive widget Template :: w3layouts</title>
</head>
<body>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="Social Login Form Widget Responsive, Login form web template,Flat Pricing tables,Flat Drop downs Sign up Web Templates, Flat Web Templates, Login signup Responsive web template, Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyEricsson, Motorola web design" />
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<!-- font files -->
<link href='/../fonts.googleapis.com/css?family=Muli:400,300' rel='stylesheet' type='text/css'>
<link href='/../fonts.googleapis.com/css?family=Nunito:400,300,700' rel='stylesheet' type='text/css'>
<!-- /font files -->
<!-- css files -->
<link href="login.css" rel='stylesheet' type='text/css' media="all" />
<!-- /css files -->
</head>
<body>
<h1>Social Login Form</h1>
<div class="log">
<div class="social w3ls">
<li class="f"><img src="images/fb.png" alt=""></li>
<li class="t"><img src="images/twt.png" alt=""></li>
<li class="p"><img src="images/pin.png" alt=""></li>
<li class="i"><img src="images/ins.png" alt=""></li>
<div class="clear"></div>
</div>
<div class="content2 w3agile">
<h2>Sign Up</h2>
<form ID="form" runat="server" method="post">
<asp:TextBox ID="name" runat="server" placeholder="Name Surname" pattern="[A-Za-z]+\s[A-Za-z]+" title="Firstname Surname" required></asp:TextBox>
<asp:TextBox ID="username" runat="server" placeholder="Username" title="Username" required></asp:TextBox>
<asp:TextBox ID="phoneno" runat="server" placeholder="Phone Number" pattern="[7-9]{1}[0-9]{9}" required title="Phone number starting with 7-9 and remaing 9 digit with 0-9"></asp:TextBox>
<asp:TextBox ID="email" type="email" runat="server" placeholder="Email Address" required ></asp:TextBox>
<asp:TextBox ID="password" runat="server" type="password" placeholder="Password" required title="Any number of characters or special characters"></asp:TextBox>
<input id="confirm_password" placeholder="Confirm Password" runat="server" type="password" required title="Any number of characters or special characters"></input>
<script type="text/javascript">
var password = document.getElementById("password")
, confirm_password = document.getElementById("confirm_password");
function validatePassword() {
if (password.value != confirm_password.value) {
confirm_password.setCustomValidity("Passwords Don't Match");
} else {
confirm_password.setCustomValidity('');
}
}
password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;
</script>
<asp:Button ID="Button1" runat="server" Text="Sign up" class="register" OnClick="btn_Click" />
<h3>Already have an account? Sign In</h3>
</div>
</div>
<div class="footer">
<p>© 2016 Social Login Form. All Rights Reserved | Design by w3layouts</p>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
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.SqlClient;
public partial class register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_Click(object sender, EventArgs e)
{
int userId = 0;
SqlConnection con = new SqlConnection(#"Data Source=RISHIK\SQLEXPRESS;Initial Catalog=Register;Integrated Security=True");
String query = "Insert into Table_2 values('"+name.Text+"','"+username.Text+"','"+phoneno.Text+"','"+email.Text+"','"+password.Text+"')";
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
userId = Convert.ToInt32(cmd.ExecuteScalar());
cmd.ExecuteNonQuery();
//Label1.Text = "Hjg";
con.Close();
}
}
this line
userId = Convert.ToInt32(cmd.ExecuteScalar());
is not doing what you think. it will execute the insert statement and then return a scalar value.
then your next line:
cmd.ExecuteNonQuery();
will insert the record again
this is what Blorgbeard is trying to tell you.
that is why it is inserting twice.
also - you should consider parameterizing that query. taking the value of your user input and creating your query with those values without checking them is just begging for a sql injection attack
Use parameterised query , something like....
int userId = 0;
SqlConnection con = new SqlConnection(#"Data Source=RISHIK\SQLEXPRESS;Initial Catalog=Register;Integrated Security=True");
SqlCommand cmd = new SqlCommand("Insert into Table_2 values(#Name, #UserName, #Phone, #Email, #Password);
SELECT CAST(scope_identity() AS int)", con);
cmd.Parameters.AddWithValue("#Name", name.Text);
cmd.Parameters.AddWithValue("#UserName", username.Text);
cmd.Parameters.AddWithValue("#Phone", phoneno.Text);
cmd.Parameters.AddWithValue("#Email", email.Text);
cmd.Parameters.AddWithValue("#Password", password.Text);
con.Open();
userId = (Int)cmd.ExecuteScalar();

AutoCompleteExtender on TextBox returns the page HTML

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;
}
}
}

Can't display results where the ending matches

I'm making a rhyme dictionary, and I have a database table with 3 coloumns, the user will search the database and the search keywords will search database where the ending of the word matches with the word in textbox.
When I enter some keyword into textbox
I get ERROR: Incorrect syntax near the keyword 'LIKE'.
This is how my database looks like
Here is how my aspx looks like:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Kafiye Dizini - Türkçe Kafiye Bulma Sözlüğü - Uyak Bulucu Sözlük - İstediğiniz harf ile biten kelimeleri bulan sözlük</title>
<meta name="description" content="İstediğiniz harfler ile biten kelimeleri bulmanızı sağlayan sözlük" />
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<link href="style.css" rel="stylesheet" />
</head>
<body>
<form id="form1" runat="server">
<div>
<div class="top">
<div class="email">İletişim: fahrettinveysel#gmail.com</div>
</div>
<div class="leftcontainer">
</div>
<div class="middlecontainer">
<div class="title">Kafiye Dizini</div>
<div class="subtitle">İstediğiniz harf veya hece ile biten kelimeleri bulmanızı sağlayan sözlük</div>
<div class="searchcontainer">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
<div class="resultboxcontainer">
<div id="resultbox1" runat="server"></div>
<div id="resultbox2" runat="server"></div>
<div id="resultbox3" runat="server"></div>
</div>
<div class="idefix"></div>
</div>
<div class="rightcontainer">
<div class="ornekarama">
<div class="ornekaramabaslik">Örnek Arama</div>
<input type="text" class="ornekaramatextbox" value="rop" disabled="disabled" />
<div class="ornekaramasonuclar">filantrop<br />gardırop<br />hipermetrop<br />mikrop<br />mizantrop</div>
</div>
</div>
</div>
</form>
</body>
</html>
and this is my aspx.cs
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
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, EventArgs e)
{
}
SqlConnection cnn = new SqlConnection("Initial Catalog=kafiyedizini;Data Source=localhost;Integrated Security=SSPI;");
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text != "")
{
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT kelime1,kelime2,kelime3 FROM kelimeler LIKE #arama", cnn);
cmd.Parameters.AddWithValue("#arama", "%" + TextBox1.Text);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
resultbox1.InnerHtml += dr.GetString(0);
resultbox2.InnerHtml += dr.GetString(1);
resultbox3.InnerHtml += dr.GetString(2);
}
}
cnn.Close();
}
else
{
resultbox1.InnerHtml += "please enter data";
}
}
}
The initial sql statement in your question should look like this
SELECT kelime1,kelime2,kelime3 FROM kelimeler where kelime1 LIKE #arama OR kelime2 LIKE #arama or kelime3 like #arama
You missed the where and the fields you want to use in your like statement.
to have each result in a separate 'box' you better investigate how a GridView works or a DataRepeater.
Closest in your initial code what could work, including support for handling null/emtpy values for one the fields returned, nicely filling the 3 resultboxes:
var f1 = dr.GetString(0);
var f2 = dr.GetString(1);
var f3 = dr.GetString(2);
if (!String.IsNullOrEmpty(f1))
resultbox1.InnerHtml += String.Format("<div>{0}</div>",f1);
if (!String.IsNullOrEmpty(f2))
resultbox2.InnerHtml += String.Format("<div>{0}</div>",f2);
if (!String.IsNullOrEmpty(f3))
resultbox1.InnerHtml += String.Format("<div>{0}</div>",f3);
You are missing WHERE part of the SQL query
Example:
SELECT * FROM test WHERE test.Id LIKE '%asd%'
I also think, dr.Read() executes PER ROW.
Hope this helps

Categories

Resources