asp.net web form button onclick event error - c#

I have asp.net web form and when Im trying to assing onclick event to a button I get following error:
Compiler Error Message: CS1061: 'ASP.webform1_aspx' does not contain a definition for 'Button1_Click' and no extension method 'Button1_Click' accepting a first argument of type 'ASP.webform1_aspx' could be found (are you missing a using directive or an assembly reference?)
Source Error:
Line 19: Line 20: Line 21:
Line 22:
Line 23:
ASP code is following:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="Form1" runat="server" method="post">
<div class="page">
<p>Persons</p>
<asp:Literal id="drpdwn" runat="server" />
<p>TransactionType</p>
<select id="sel" runat="server">
<option>bilance </option>
<option>liekākais parādnieks un aizdevējs</option>
<option>vidējais aizņēmuma lielums</option>
</select>
<asp:Button ID="Button1" runat="server" Text="Click Me" OnClick="Button1_Click" />
<table id="HTMLTable" width="300px;" runat="server">
<tr>
<td>
<b></b>
</td>
</tr>
</table>
</div>
</form>
</body>
<script type="text/javascript" >
var yourSelect = document.getElementById("sel");
var asdasd = yourSelect.options[yourSelect.selectedIndex].value;
</script>
</html>
And Codebehind is following:
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.Data;
using System.Web.UI.HtmlControls;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//int selectedIndex = (sel as HtmlSelect).SelectedIndex;
sel.Value.ToString();
SqlConnection cnn = new SqlConnection();
SqlDataReader rdr = null;
SqlCommand command = new SqlCommand();
cnn.ConnectionString = #"Server=localhost;Database=TildeTest;uid=AdminUser;pwd=AdminPwd;app=WebApplication1;";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string CommandText = "select * from persons";
command = new SqlCommand(CommandText);
command.CommandType = CommandType.Text;
//command.Connection = cnn;
try
{
cnn.Open();
command.Connection = cnn;
rdr = command.ExecuteReader();
if (rdr.HasRows)
{
drpdwn.Text = "<select>";
drpdwn.Text += "<option> </option>";
while (rdr.Read())
{
drpdwn.Text += "<option>" + rdr.GetString(1) + "</option>";
}
drpdwn.Text += "</select>";
}
else
{
Console.WriteLine("No rows found.");
}
rdr.Close();
}
catch (Exception ex)
{
Console.WriteLine(e.ToString());
}
finally
{
if (cnn.State == ConnectionState.Open)
cnn.Close();
}
}
void Button1_Click(Object sender,
EventArgs e)
{
// do something
}
}
}

you can change void Button1_Click to protected void Button1_Click and try.

Assuming you are using visual studio, double click the button from design view, then write the code behind inside the generated function. That should work.

Related

Image not loading for Carousel

I am trying to publish images in Carousel. But Image not loading. Anyone can help will be highly appreciated. Following is the code:
carousel_test.aspx file code below. Here , through Rgallery, I am trying to display carousel images.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="carousel_test.aspx.cs" Inherits="reader.carousel_test" %>
<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="css/style.css">
<!--Carousel -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<!--Carousel -->
<body>
<form id="form1" runat="server" style="font-size: small">
<div id="myCarousel" class="carousel slide">
<div class="carousel-inner">
<asp:Repeater ID="Rgallary" runat="server">
<ItemTemplate>
<div class="item" >
<div class="item active">
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "ImageHandler.ashx?ImID="+ Eval("product_sell_code") %>' />
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
//This is used for manual navigation like for next or previous
<a class="carousel-control left" href="#myCarousel" data-slide="prev">‹</a>
<a class="carousel-control right" href="#myCarousel" data-slide="next">›</a>
</div>
</form>
</body>
<script type="text/javascript">
$(document).ready(function () {
$('.carousel').carousel({
interval: 2500
})
});
</script>
carousel_test.aspx.cs file code below. This is code file, where I am calling for loading image from database.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
namespace reader
{
public partial class carousel_test : System.Web.UI.Page
{
string sq = ConfigurationManager.ConnectionStrings["readerConnStr"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindslide();
}
}
public void bindslide()
{
SqlConnection connection = new SqlConnection(sq);
using (SqlCommand cmd = new SqlCommand("select product_sell_code from product_for_sell ", connection))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
Rgallary.DataSource = ds;
}
Rgallary.DataBind();
connection.Dispose();
connection.Close();
}
}
}
ImageHandler.ashx.cs is the Image Handler File
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace reader
{
/// <summary>
/// Summary description for $codebehindclassname$
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class ImageHandler : IHttpHandler
{
SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["readerConnStr"].ToString());
/* string strcon = ConfigurationManager.AppSettings["readerConnStr"].ToString(); */
public void ProcessRequest(HttpContext context)
{
string imageid = context.Request.QueryString["ImID"];
/* SqlConnection connection = new SqlConnection(strcon);*/
connection.Open();
SqlCommand command = new SqlCommand("select product_image from product_for_sell where product_sell_code=" + imageid, connection);
SqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
connection.Close();
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
Here is the code. Please help

The name 'UName' does not exist in the current context

When trying to register to my database I am receiving the "The name 'UName' does not exist in the current context" error.
Register.aspx:
<%# 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>Registration Page</title>
</head>
<body>
<p>This is the registration page</p>
Home | Register
<form id="form1" runat="server">
<div>
<p>Enter First Name :</p>
<p>
<asp:TextBox ID="UName" runat="server" Width="271px"></asp:TextBox>
</p>
<p>
<asp:Button ID="registerButton" runat="server" Text="REGISTER" OnClick="registerEventMethod" />
</p>
</div>
</form>
</body>
</html>
Register.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Register : System.Web.UI.Page
{
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
String queryStr;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void registerEventMethod(object sender, EventArgs e)
{
registerUser();
}
private void registerUser()
{
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "";
queryStr = "INSERT INTO jamieobr_obecarrentals.users (Forename)" +
"VALUES('" + UName.Text + "')";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
cmd.ExecuteReader();
conn.Close();
}
}
why am I getting this error? I have tried several solutions and all failed.
So I solved my own issue, the first initial issue was that I tried copying the .aspx file into a new solution, however this did not copy along the .aspx.designer.cs file therefore causing the problem.
However after trying to re write a fresh version manually which had a designer file with it I forgot to include the .cs file into the namespace of my solution therefore then generating a new problem.
However after including the .cs file into the namespace, hey presto, it worked!

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

ASP.NET report with parameter

I have a stored procedure named "Graph" that should get a value to the parameter #Material, and I created a report in ASP.NET that should show a chart using the data from the stored procedure.
However, when I try to load the report I get:
An error has occurred during report processing.
Cannot create a connection to data source 'PhilipsMaterialsDataSet'.
ObjectDataSource 'ObjectDataSource1' could not find a non-generic method 'GetData' that has no parameters.
I tried different solutions but none of them worked. Also, I'm not sure if I should declare the parameter in the ASP code.
( by the way, GetData is not recognized here because it has one parameter (#Material-from the stored procedure) and for some reason, it is called without any parameters )
The code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Reporting.WebForms;
public partial class StatisticsPage : System.Web.UI.Page
{
string Connectionstring = "server=(local)\\SQLEXPRESS;database=PhilipsMaterials;Integrated Security=SSPI";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
protected void btndisplay_Click(object sender, EventArgs e)
{
BindReport();
}
private void BindReport()
{
SSRSReport report = new SSRSReport();
SqlParameter[] sqlParams = new SqlParameter[] {
new SqlParameter("#Material","453567068441")
};
string ReportDataSource = "DataSet1";
bool bind = report.CreateReport(Connectionstring, "graph", sqlParams, ref ReportViewer1, ReportDataSource);
if (bind)
{
ReportViewer1.Visible = true;
}
}
}
public class SSRSReport
{
public SSRSReport()
{
//
// TODO: Add constructor logic here
//
}
public bool CreateReport(String Connectionstring,string StoreProcedureName ,SqlParameter[] Parameter,ref Microsoft.Reporting.WebForms.ReportViewer ReportViewer,string ReportDataSource)
{
bool reportbind = false;
using (SqlConnection con = new SqlConnection(Connectionstring))
{
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = StoreProcedureName;
com.Parameters.AddRange(Parameter);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(com);
da.Fill(ds);
ReportDataSource datasource = new ReportDataSource(ReportDataSource, ds.Tables[0]);
if ( ds.Tables[0].Rows.Count > 0)
{
ReportViewer.LocalReport.DataSources.Clear();
ReportViewer.LocalReport.DataSources.Add(datasource);
//This is another solution I tried:
//List<ReportParameter> lstReportParameters = new List<ReportParameter>();
//ReportParameter objReportParameter = new ReportParameter("Material", "453567068441");
//lstReportParameters.Add(objReportParameter);
//ReportViewer.LocalReport.SetParameters(lstReportParameters);
// ReportViewer.ServerReport.Refresh();
reportbind = true;
}
}
return reportbind;
}
}
The ASP code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="StatisticsPage.aspx.cs" Inherits="StatisticsPage" %>
<%# Register assembly="Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" namespace="Microsoft.Reporting.WebForms" tagprefix="rsweb" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Test SSRS</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<rsweb:ReportViewer ID="ReportViewer1" runat="server" Font-Names="Verdana" Font-Size="8pt" WaitMessageFont-Names="Verdana" WaitMessageFont-Size="14pt" Height="610px" Width="1179px" ShowParameterPrompts="true">
<LocalReport ReportPath="Report.rdlc" >
<DataSources>
<rsweb:ReportDataSource DataSourceId="ObjectDataSource1" Name="DataSet1" />
</DataSources>
</LocalReport>
</rsweb:ReportViewer>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetData" TypeName="PhilipsMaterialsDataSetTableAdapters.GraphTableAdapter" >
</asp:ObjectDataSource>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
</form>
</body>
</html>
public DataSet CreateReport(String Connectionstring,string StoreProcedureName ,SqlParameter[] Parameter,ref Microsoft.Reporting.WebForms.ReportViewer ReportViewer,string ReportDataSource) {
//return the dataset
}
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
SelectMethod="CreateReport" TypeName="SqlHelper" />
can u try to change ur method return value to DataSet..
and in the codebehind try to databind to that method..
Maybe it might work..

ASP.NET report with a parameter

I have a stored procedure named "Graph" that should get a value to the parameter #Material, and I created a report in ASP.NET that should show a chart using the data from the stored procedure.
However, when I try to load the report I get:
An error has occurred during report processing.
Cannot create a connection to data source 'PhilipsMaterialsDataSet'.
ObjectDataSource 'ObjectDataSource1' could not find a non-generic method 'GetData' that has no parameters.
I tried different solutions but none of them worked. Also, I'm not sure if I should declare the parameter in the ASP code.
( by the way, GetData is not recognized here because it has one parameter (#Material-from the stored procedure) and for some reason, it is called without any parameters )
The code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Reporting.WebForms;
public partial class StatisticsPage : System.Web.UI.Page
{
string Connectionstring = "server=(local)\\SQLEXPRESS;database=PhilipsMaterials;Integrated Security=SSPI";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
protected void btndisplay_Click(object sender, EventArgs e)
{
BindReport();
}
private void BindReport()
{
SSRSReport report = new SSRSReport();
SqlParameter[] sqlParams = new SqlParameter[] {
new SqlParameter("#Material","453567068441")
};
string ReportDataSource = "DataSet1";
bool bind = report.CreateReport(Connectionstring, "graph", sqlParams, ref ReportViewer1, ReportDataSource);
if (bind)
{
ReportViewer1.Visible = true;
}
}
}
public class SSRSReport
{
public SSRSReport()
{
//
// TODO: Add constructor logic here
//
}
public bool CreateReport(String Connectionstring,string StoreProcedureName ,SqlParameter[] Parameter,ref Microsoft.Reporting.WebForms.ReportViewer ReportViewer,string ReportDataSource)
{
bool reportbind = false;
using (SqlConnection con = new SqlConnection(Connectionstring))
{
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = StoreProcedureName;
com.Parameters.AddRange(Parameter);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(com);
da.Fill(ds);
ReportDataSource datasource = new ReportDataSource(ReportDataSource, ds.Tables[0]);
if ( ds.Tables[0].Rows.Count > 0)
{
ReportViewer.LocalReport.DataSources.Clear();
ReportViewer.LocalReport.DataSources.Add(datasource);
//This is another solution I tried:
//List<ReportParameter> lstReportParameters = new List<ReportParameter>();
//ReportParameter objReportParameter = new ReportParameter("Material", "453567068441");
//lstReportParameters.Add(objReportParameter);
//ReportViewer.LocalReport.SetParameters(lstReportParameters);
// ReportViewer.ServerReport.Refresh();
reportbind = true;
}
}
return reportbind;
}
}
The ASP code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="StatisticsPage.aspx.cs" Inherits="StatisticsPage" %>
<%# Register assembly="Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" namespace="Microsoft.Reporting.WebForms" tagprefix="rsweb" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Test SSRS</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<rsweb:ReportViewer ID="ReportViewer1" runat="server" Font-Names="Verdana" Font-Size="8pt" WaitMessageFont-Names="Verdana" WaitMessageFont-Size="14pt" Height="610px" Width="1179px" ShowParameterPrompts="true">
<LocalReport ReportPath="Report.rdlc" >
<DataSources>
<rsweb:ReportDataSource DataSourceId="ObjectDataSource1" Name="DataSet1" />
</DataSources>
</LocalReport>
</rsweb:ReportViewer>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetData" TypeName="PhilipsMaterialsDataSetTableAdapters.GraphTableAdapter" >
</asp:ObjectDataSource>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
</form>
</body>
</html>
The error is saying GetData requires some parameters, and you have to supply them by adding a parameters like like:
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetData" TypeName="PhilipsMaterialsDataSetTableAdapters.GraphTableAdapter" >
<SelectParameters>
<asp:Parameter Name="X" DefaultValue="Y" .. />
</SelectParameters>
</asp:ObjectDataSource>

Categories

Resources