Save texbox text to SQL Server in ASP.NET website - asp.net

I have a website in ASP.NET and I have a textbox that the user type in text. I want to save this into a SQL Server database that saves all other data from site. I have tried several ways and got to the code below. It throws up the error below
Any help as I'm lost on this now....
Error:
The name 'txtName' does not exist in the current context Step9.aspx.cs 67
Page markup:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Step9.aspx.cs" Inherits="Step1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div class="question" id="question">
<table border="1" style="border-collapse: collapse">
<tr>
<td style="width: 150px">
Name:<br />
<asp:TextBox ID="txtName" runat="server" Width="140" />
</td>
<td style="width: 100px">
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Insert" />
</td>
</tr>
</table>
</div>
</asp:Content>
C# codebehind:
protected void Insert(object sender, EventArgs e)
{
string name = txtName.Text;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO learners (stickTwistBefore) VALUES (#stickTwistBefore)"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Parameters.AddWithValue("#stickTwistBefore", name);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
// this.BindGrid();
}

I noticed that you have specified Step1 class name as Inherits attribute. Ensure that it matches the class name in your Step9.aspx.cs file. I guess Step9 but just confirm.
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Step9.aspx.cs" Inherits="Step1" %>

Related

SQL Database not working with ASP.NET web form

I am designing a web form on Visual Studio 2010 using ASP.NET framework. I am using SQL Database to connect my web form to the server, but there are some errors which I can't resolve?
Any help would be greatly appreciated.
I am trying to run a web form that connects to the database which when data entered into the form, stores the information into the server for the user to login later
The following is the code for the web form.
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 _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=#"C:\Users\Kapalmeet Singh\Desktop\WebSite1\App_Data\Database.mdf";Integrated Security=True;User Instance=True")
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Table1 values('"+TextBox1.Text+"','"+TextBox2.Text+"','"+TextBox3.Text+"','"+TextBox4.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
}
}
And here's the code for the web form
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>
<style type="text/css">
.style1
{
width: 100%;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<table class="style1">
<tr>
<td>
First Name</td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Last Name</td>
<td>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
User Name</td>
<td>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Password</td>
<td>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</td>
</tr>
</table>
<div>
</div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
style="margin-left: 192px" Text="Submit" />
</form>
</body>
</html>
If your creating a registration it would be like this. Change the names for these the way they are called in your database and for the other ones to. (#FirstName, #Surname, #Password, #Username,)
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["YOUR_CONNECION_STRING_HERE"].ConnectionString);
conn.Open();
string insertQuery = "insert into Table1(FirstName, Surname, Username, Password) " +
"values(#FirstName, #Surname, #Password, #Username,)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("#FirstName", Textbox1.Text);
com.Parameters.AddWithValue("#Surname", Textbox2.Text);
com.Parameters.AddWithValue("#Password", Textbox3.Text);
com.Parameters.AddWithValue("#Username", Textbox4.Text);
//This actually executes the query with the given values above.
com.ExecuteNonQuery();
conn.Close();
Response.Redirect("Name_Of_Any_Page_Thats_On_Your_Site.aspx");
Response.Write("there was a problem with your registration");
}
catch (Exception problem)
{
//throw Exception ;
Response.Write("Error Message: " + problem.ToString());
throw;
}

cannot resolve symbol

i have made a simple table (lets call it volunteers), but when i want to call it in my code behind Visual studio can not recognize it. The error is cannot resolve symbol 'volunteers'.
here is the code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="root_VerifyUsers.aspx.cs"
MasterPageFile="~/Root.Master" %>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<p>
<asp:Table runat="server" ID="volunteers" ForeColor="Green" Width="100%" Height="85%" BorderColor="Red"></asp:Table>
<asp:TableHeaderCell ID="NationalId" runat="server">National Id</asp:TableHeaderCell>
<asp:TableHeaderCell ID="Email" runat="server">Email</asp:TableHeaderCell>
</p>
</asp:Content>
that is behind code:
public partial class RootVerifyUsers : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TableRow tr = new TableRow();
TableCell fname = new TableCell();
TableCell NationalId=new TableCell();
tr.Cells.Add(NationalId);
volunteers.Rows.add(tr);
}
}
The problem solved by adding this attribute
Inherits="Library.Account.RootVerifyUsers"
Thanks everyone for helping
Your TableHeaderCell should be inside Table tag
<asp:Table runat="server" ID="volunteers" ForeColor="Green" Width="100%" Height="85%" BorderColor="Red">
<asp:TableHeaderCell ID="NationalId" runat="server">National Id</asp:TableHeaderCell>
<asp:TableHeaderCell ID="Email" runat="server">Email</asp:TableHeaderCell>
</asp:Table>
You have asp:TableHeaderCell with an id of NationalId and a local variable called NationalId:
TableCell NationalId=new TableCell();
That isn't going to work... Change one of them to start with..
Also, have a look at the examples on MSDN here, to correctly structure your <asp:Table...

" " Does not exist in current context?

Im making a website that sends information to a mysql server, using asp.net. code. The problem Im having is that when i debug the code and launch the page, I get these error:
Im not sure why, I have this error.
Here is my code:
Default.aspx
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default"%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<form id="form1" runat="server">
<div>
<table width="300px" >
<tr>
<td>First Name</td>
<td>
<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td >Last Name</td>
<td>
<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>User Name</td>
<td>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Password</td>
<td>
<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Email Address</td>
<td>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td> </td>
<td>
<asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
</td>
</tr>
<tr>
<td> </td>
<td>
<asp:Label ID="lblError" runat="server" Text=""></asp:Label>
</td>
</tr>
</table>
</div>
</form>
</asp:Content ID="Content1" runat="server" ContentPlaceHolderID="MainContent">
Default.aspx.cs
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
string cnnString = "Server=localhost;Port=1111;Database=ci_series;Uid=asdfasdf;Pwd=*******";
MySqlConnection connection = new MySqlConnection(cnnString);
string cmdText = "INSERT INTO membership (first_name ,last_name ,username ,password ,";
cmdText += "email_address)VALUES (first_name ,last_name ,username ,password ,email_address);";
MySqlCommand cmd = new MySqlCommand(cmdText, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("?first_name", MySqlDbType.VarChar).Value = txtFirstName.Text;
cmd.Parameters.Add("?last_name", MySqlDbType.VarChar).Value = txtLastName.Text;
cmd.Parameters.Add("?username", MySqlDbType.VarChar).Value = txtUserName.Text;
cmd.Parameters.Add("?password", MySqlDbType.VarChar).Value = txtPassword.Text;
cmd.Parameters.Add("?email_address", MySqlDbType.VarChar).Value = txtEmail.Text;
connection.Open();
int result = cmd.ExecuteNonQuery();
lblError.Text = "Data Saved";
}
catch (Exception ex)
{
lblError.Text = ex.Message;
}
}
}
How Do i Fix this? What does "Not exist in the current context" mean? Thanks in advance!
1) Make sure runat="server" is on the html tag on your master page.
2) Sometimes you get this error due to and assembly caching problem because VS gets confused about what actually needs to be recompiled. -- I just delete the cache items and recompile normally, figuring that more than 1 thing may be wrong
You have 2 issues
</asp:Content> instead </asp:Content ID="Content1" runat="server" ContentPlaceHolderID="MainContent"> . It's already put the comment from piLHa
You don't need form tagin content page . the form tag was already defined in master page , so please remove the form tag in your content page.
I had a similar issue when getting old VS2005 aspx/aspx.cs files into a new project in VS2013. I resolved this by creating a new web application, creating a new webform for each aspx page and copying the code for .aspx and .cs. Once copied I have to change the .cs files first line to use CodeBehind instead of CodeFile .
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="_Login" %>
TO
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="_Login" %>
I hope this helps someone else.
I got same problem when i was coding with c# aspx and i figured out this like that:
I had deleted this Inherits="project_name.ClassName" from my XXX.aspx file mistakenly which is first line in my XXX.aspx file.. And then when i added Inherits="project_name.ClassName" this code to my XXX.aspx first line to my file and then it solved my problem. You should make control your first line in your XXX.aspx file, you could delete Inherits="project_name.ClassName" wrongly....
I hope you will figure out the problem for this answer.
Good luck
Replace below code of .aspx page in #page tag
Replace this: <%# Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="Namespace.Test" %>
Replace with: <%# Page Language="C#" AutoEventWireup="true" CodeFile="~/Test.aspx.cs" CodeBehind="Test.aspx.cs" Inherits="Namespace.Test" %>
Right_click on "WebApplication"
and Click on "Convert to Web Application "

ASP.NET dataset add relation null reference exception

I'm using this article as a guide to doing a nested data bind of my two tables 'Comment' 'CommentOtherAuthor': http://support.microsoft.com/kb/306154. There may be many authors to one comment. The code I have is here:
.ASPX:
<asp:Repeater ID="rptComments" runat="server">
<ItemTemplate>
<div class="comment-data">
<h3 class="item">Submitted to <%# GetPageDetails(Eval("nodeid")) %> article on <%# Eval("created") %></strong></h3>
<p class="item"><strong>Name</strong> <%# Eval("firstname") %> <%# Eval("surname") %></p>
<p class="item"><strong>Occupation</strong> <%# Eval("occupation") %></p>
<p class="item"><strong>Affiliation</strong> <%# Eval("affiliation") %></p>
<p class="item"><strong>Email</strong> <a href='mailto:<%# Eval("email") %>'><%# Eval("email") %></a> <em>Publish email: <%# Eval("publishemail") %></em></p>
<p class="item"><strong>Competing interests?</strong> <%# Eval("competingintereststext") %> </p>
<p class="item"><strong>eLetter title</strong> <%# Eval("title") %></p>
<p><%# Eval("comment").ToString().Replace("\n", "<br/>")%></p>
<div class="additional-authors">
<h3>Additional authors</h3>
<asp:Repeater id="rptAdditionalAuthors" runat="server" datasource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("myrelation") %>' >
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "[\"firstname\"]")%><br>
</ItemTemplate>
</asp:Repeater>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
Codebehind:
private void BindData()
{
SqlConnection cnn = new SqlConnection(GlobalSettings.DbDSN);
SqlDataAdapter cmd1 = new SqlDataAdapter(string.Format("select * from Comment {0} order by created desc", Filter), cnn);
//Create and fill the DataSet.
DataSet ds = new DataSet();
cmd1.Fill(ds, "comments");
//Create a second DataAdapter for the additional authors table.
SqlDataAdapter cmd2 = new SqlDataAdapter("select * from CommentOtherAuthor", cnn);
cmd2.Fill(ds, "additionalAuthors");
//Create the relation between the comments and additional authors tables.
ds.Relations.Add(
"myrelation",
ds.Tables["Comment"].Columns["id"],
ds.Tables["CommentOtherAuthor"].Columns["commentid"]
);
//Bind the Authors table to the parent Repeater control, and call DataBind.
rptComments.DataSource = ds.Tables["additionalAuthors"];
rptComments.DataBind();
}
However, when running this it throws a System.NullReferenceException on the line ds.Relations.Add(
I'm really not sure where to start in fixing this as I'm way out of my depth here.
Can anyone advise how to get this working?
Thanks.
Got it! There was no actual foreign key constraint joining the tables. With that in place this now works.

Cannot Bind my Listview

I want to bind my Listview but I can't. I dont know what I am doing wrong here. When I press ctrl+f5, the page is empty.
My Code is:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:ListView ID="ListView1" runat="server" DataKeyNames="Student_ID">
<LayoutTemplate>
<table id="itemplaceholderContainer" runat="server">
<tr id="itemplaceholder">
<td>
Student ID :
</td>
<td>
Registration Number :
</td>
<td>
Student Name :
</td>
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
StudentID:
<asp:Label ID="LabelID" runat="server" Text='<%Eval("Student_ID") %>'></asp:Label>
StudentRegistrationNumber:<asp:Label ID="LabelNumber" runat="server" Text='<%Eval("StudentRegistrationNumber") %>'></asp:Label>
StudentName:<asp:Label ID="LabelName" runat="server" Text='<%Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:ListView>
</asp:Content>
Codebehind is :
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(#"Data Source=LOCALHOST;Initial Catalog=ITCF;Integrated Security=True");
SqlCommand cmd = new SqlCommand("Select * from Student", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.fill(dt);
ListView1.DataSource = dt;
ListView1.DataBind();
}
try this:
first your item template is worng, and also you need to fill the data adabter form the Data Table
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:ListView ID="ListView1" runat="server" DataKeyNames="Student_ID">
<LayoutTemplate>
<table id="itemplaceholderContainer" runat="server">
<tr id="itemplaceholder">
<td>
Student ID :
</td>
<td>
Registration Number :
</td>
<td>
Student Name :
</td>
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
StudentID:
<asp:Label ID="LabelID" runat="server" Text='<%# Eval("Student_ID") %>'></asp:Label>
StudentRegistrationNumber:<asp:Label ID="LabelNumber" runat="server" Text='<%# Eval("StudentRegistrationNumber") %>'></asp:Label>
StudentName:<asp:Label ID="LabelName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:ListView>
</asp:Content>
Codebehind is :
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(#"Data Source=LOCALHOST;Initial Catalog=ITCF;Integrated Security=True");
SqlCommand cmd = new SqlCommand("Select * from Student", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
ListView1.DataSource = dt;
ListView1.DataBind();
}
The last 3 lines of code in your code-behind tell the whole story:
DataTable dt = new DataTable();
ListView1.DataSource = dt;
ListView1.DataBind();
You're instantiating a new, empty DataTable and binding ListView1 to it. Thus, behaving correctly and exactly as designed, your ListView is displaying zero records from the empty DataTable.
You'll want to fetch the data from the DataAdapter before you bind anything to it. Something like this:
var students = new DataSet();
da.Fill(students, "Student");
if (students.Tables.Count == 1)
{
ListView1.DataSource = students.Tables[0];
ListView1.DataBind();
}
Note: There may be a more direct way to fetch the DataTable. I haven't worked with DataSets and DataTables in a long time, but .Fill() may be able to directly use a DataTable and skip my checking of a valid table in the DataSet above.)
Your datatable is never getting populated. Have a look at the following:
http://msdn.microsoft.com/en-us/library/bh8kx08z.aspx

Resources