My web form is not saving to database successfully - c#

My form doesn't save the text in the Texbox to the database. I've probably something wrong in my .cs CodeFile, but I can't work it out.
It could well be my connection string.
My web form:
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
Enter selection text:
</td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
<td colspan="2" align="center">
<asp:Button ID="Button1" runat="server" Text="Submit" />
</td>
</tr>
</table>
</div>
</form>
Here is my code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source=db65225900.db.1and1.com; Initial Catalog=db211255182; User ID=dbo652259000; Password=Password");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into homepageSelection values('"+TextBox1.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
}
}
My MsSQL is setup like the following:
1 column: selectionText nvarchar(3000)

Missing button click event definition in aspx
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click1" />
---------------^

SqlConnection is for SQL Server. You need MySqlConnection - This is not part of the .NET Framework. So it is a better approach if you will also have to use the MySqlCommand object rather than the SqlCommand object.
This is MySql and not SQL. So you need to get connected to MySql. For this you need to download and installed the MySQL Connector/NET from the MySQL official website.
Then probably you can look at Connect C# to MySQL to see how to get connected with MySQL Database and run the different Insert, Update, Select, Delete commands using C#
Last but not the least you have to include OnClick="Button1_Click1" with your asp:Button

You need to set the colum name in insert statement
cmd.CommandText = "insert into homepageSelection (ColumnName) values('"+TextBox1.Text+"')";
also you missed click event
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click1" />

Related

Populating a listbox with search results from a SQL query in ASP.NET and C#

The idea behind the program is for a user to enter a title they would like to search for and then click on the search button. The program should then display the search results in a listbox. The current code populates the listbox with all the available titles when the from loads but when you search for a title the listbox stays the same. How can I avoid the population of the listbox when the form loads and how do I only display the search result when the user clicks the search button?
Here is the C# code I have written:
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.Configuration;
namespace Project2
{
public partial class ProductSelection : System.Web.UI.Page
{
public SqlConnection conn1;
public DataSet ds;
public SqlDataAdapter adap;
string DVDToRent;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string constr = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Hanno\Desktop\CMPG\CMPG212\Project 2\Project2\Project2\App_Data\Stock.mdf;Integrated Security=True";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT ID, Title FROM StockTable WHERE Title LIKE '%" + Session["DVDToRent"] + "%' AND CopiesAvailable = 'True'"))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
lstCustomers.DataSource = cmd.ExecuteReader();
lstCustomers.DataTextField = "Title";
lstCustomers.DataValueField = "ID";
lstCustomers.DataBind();
con.Close();
}
}
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
DVDToRent = tbSearch.Text;
Session["DvDToRent"] = tbSearch.Text;
}
}
}
and the ASP.NET markup for the listbox:
<div class="formSearch" runat="server">
<div class ="form-group">
<h2 class="auto-style2">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</h2>
</div>
<div class="form-group">
<asp:Label ID="Label2" runat="server" Text="Search for a DVD:"></asp:Label>
<br />
<asp:TextBox ID="tbSearch" runat="server"></asp:TextBox>
</div>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />
<div class="form-group">
<asp:Label ID="Label3" runat="server" Text="Search Results:"></asp:Label>
<br />
<asp:ListBox ID="lstCustomers" runat="server" AutoPostBack="True" Width="400px"></asp:ListBox>
</div>
</div>

Button inside every product

I am doing a little school project with ASP.NET, and I'm trying to get all products from the Database, show it and have "Add to card" button for every one of them. I managed to do all this, except adding the button. I have a function that gets all the products and I'm binding it with ASP Repeater. The problem is, when I try to add a button, it says that I need to use the form tag first, when I add the form tag it says it needs to have runat="server", but when I add it, it says I can't have more than one runat="server". The Repeater tag is using it also, and I'm stuck. Can anyone suggest something? Thank you!
private void bindPopularProducts()
{
String CS = ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Food", con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable fFood = new DataTable();
sda.Fill(fFood);
popularFood.DataSource = fFood;
popularFood.DataBind();
}
}
}
}
and this
<asp:Repeater ID="popularFood" runat="server">
<ItemTemplate>
<div class="col-md-4">
<div><%# Eval("name") %></div>
<div><asp:Image ID="foodImage" runat="server" ImageUrl='<%# "~/images/food/" + Eval("image").ToString() %>' Visible="true" CssClass="img-responsive" /></div>
<div>
<div class="col-md-4 text-left"><%# "$"+Eval("price_small")+"/small" %></div>
<div class="col-md-8 text-right">
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
I'm trying to put the button inside the text-right div
Within your Repeater's ItemTemplate, add a button. In the button, set the CommandArgument to some key value that uniquely identifies the product.
<asp:Button ID="Button1" runat="server" Text="Click Me" CommandArgument='<%# Eval("Product.Key") %>' OnClick="Button1_Click" />
In your code, the event handler can use the button's CommandArgument to get the product key and execute your "Add to card" method.
protected void Button1_Click(object sender, EventArgs e)
{
string myProductKey;
// Use "myProductKey" to do something with the Product record...
myProductKey = ((Button)sender).CommandArgument;
}

Another Populate Dropdownlist from another Dropdownlist selected value using stored procedure

I have found several solutions online for similar topic but I have not found any clear solution and explanations for the case I am dealing with. Here are the questions/areas I needed helps with:
How to populate the second Dropdownlist (EmailDDL) with the Contact Information (Email) based on the selected Company in the first Dropdownlist (CompanyDDL). Two things I wanted to pointed out here are:
a. I have only ONE table Not two and I have no associate IDs as mentioned in other solution. (see below)
b. I am using Stored Procedure in my code behind (see below)
I am not so clear on the differences between OnSelectedIndexChanged="ContactEmailList_SelectedIndexChanged" and how my sproc2 storedprocedure filters the email list by using #Company value. Would some one share the knowledges? In another word, how the selected value in the first dropdownlist passed to the stored procedure sproc2?
I have no problem populate the first dropdownlist using just the dropdownlist asp control without having to use Dataset or SqlDataAdapter . Would I need to use those for the second dropdownlist?
So far I get the 1st dropdown (Companies list) and a long list of all emails in the second dropdownlist (ContactEmail). I need to have the second list filtered by the first one. Please helps. If it is possible a step by step approach with illustrated code sample would be very heplful and appreciated.
Thanks
Background Info:
2 stored procedures: sproc1 and sproc2 and 1 SQL table ( ContactInfo) with 3 columns:
Company, ContactName, ContactEmail.
sproc1: procedure [dbo].[sproc1]
as
begin
Select distinct [Company] From [ContactInfo]
end
sproc2: procedure [dbo].[sproc2] #Company nvarchar(50) = null
as
begin
Select distinct [ContactName],[ContactEmail] From [ContactInfo]
where [Company] = #Company
end
aspx:
//First Dropdownlist:
<p>Company:<br />
<asp:DropDownList ID="Company_DDList" runat="server"
Width="355px" Height="24px"
DataSourceID="ContactInfo"
DataTextField="Company"
DataValueField="Company"
AutoPostBack="true"
AppendDataBoundItems="true"
onselectedindexchanged =
"Company_DDList_SelectedIndexChanged">
<asp:ListItem Enabled="true"
Selected="True"
Text="-- select --">
</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="ContactInfo" runat="server"
ConnectionString="<%$ ConnectionStrings:My_ConnectionString %>"
SelectCommand="sproc1"
SelectCommandType="StoredProcedure">
</asp:SqlDataSource>
//Second Dropdownlist:
<p>Contact:<br />
<asp:DropDownList ID="Contact_DDList" runat="server"
Width="355px" Height="24px"
DataSourceID="ContactInfo"
DataTextField="Email"
DataValueField="Email"
AutoPostBack="true"
AppendDataBoundItems="true"
onselectedindexchanged="Contact_DDList_SelectedIndexChanged">
<asp:ListItem Enabled="true"
Selected="True"
Text="-- select --">
</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="ContactInfo" runat="server"
ConnectionString="<%$ ConnectionStrings:My_ConnectionString %>"
SelectCommand="sproc2"
SelectCommandType="StoredProcedure">
</asp:SqlDataSource>
aspx.c //////////////////////////////
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;
using System.Net.Mail;
using System.Net;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
public string query;
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings
["MyConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
con.Open();
//SubmitButton.Enabled = false;
//Label1.Visible = false;
}
protected void Company_DDList_SelectedIndexChanged(object sender, EventArgs
e)
{
query = "sproc2";
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.StoredProcedure;
?????
}
protected void Contact_DDList_SelectedIndexChanged(object sender, EventArgs
e)
{
//
{
you can call second dropdown change event after complete first dropdown
protected void Company_DDList_SelectedIndexChanged(object sender, EventArgs
e)
{
query = "sproc2";
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.StoredProcedure;
Contact_DDList_SelectedIndexChanged(sender, e);
}
the below code call second dropdown change event after first dropdown chagnes. try it.

AutoComplete functionality not firing

I have a project that is using ASP.NET 4.5 and C#. I have a textbox server control that is tied to a asp AutoCompleteExtender. The problem is that it seems to either not be connection to the database to there is a bug somewhere in my code. For this I am not using a web service just a simple aspx and aspx.cs code behind. I haven't been able to debug to pinpoint the actual problem yet because I am getting the
uncaught exception thrown by method called through reflection
and am in the process of figuring out what is causing that problem.
Here is my textbox control:
<div class="col-md-10">
<asp:TextBox ID="txtContactsSearch" runat="server"></asp:TextBox>
<cc1:AutoCompleteExtender ServiceMethod="SearchCustomers"
MinimumPrefixLength="2"
CompletionInterval="100" EnableCaching="false" CompletionSetCount="10"
TargetControlID="txtContactsSearch"
ID="AutoCompleteExtender1" runat="server" FirstRowSelected="false">
</cc1:AutoCompleteExtender>
<asp:RequiredFieldValidator runat="server" ControlToValidate="StudentID" CssClass="text-danger" Display="Dynamic" ErrorMessage="The student ID field is required." />
</div>
And I have the AJAX directive on the declared on the aspx page aswell:
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
And this is the code behind that implements the functionality for the AutoComplete:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class SearchStudent : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> SearchStudents(string prefixText, int count)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Fname from Student_Registration_Form where " +
"Fname like #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Connection = conn;
conn.Open();
List<string> students = new List<string>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
students.Add(sdr["Fname"].ToString());
}
}
conn.Close();
return students;
}
}
}
}
The issue which caught my attention is: You are calling wrong method in your Autocomplete extender
<cc1:AutoCompleteExtender ServiceMethod="SearchCustomers"
public static List<string> SearchStudents(string prefixText, int count)
{
Here you can see you have passed SearchCustomers as ServiceMehtod but in your page you are using SearchStudents.
Recently I have tried twitter's TypeAhead autocomplete plugin which is easy and fast as compare to Autocomplete Extender. Have a look you might like :
Textbox autocomplete using twitter typeahead in asp .net
[I think you have used this link for your reference .But it worked for me.][1]
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.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
namespace AutoComplete
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetCompletionList(string prefixText, int count)
{
using (SqlConnection conn = new SqlConnection())
{
try
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["Default"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select LoginName from Users where " +
"LoginName like #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Connection = conn;
conn.Open();
List<string> students = new List<string>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
students.Add(sdr["LoginName"].ToString());
}
}
conn.Close();
return students;
}
}
catch (Exception ex)
{
return null;
}
}
}
}
}
ASPX Code:
<table style="margin-top: 40px; color: White">
<tr>
<td>
Search County
</td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ServiceMethod="GetCompletionList" MinimumPrefixLength="1"
CompletionInterval="10" EnableCaching="false" CompletionSetCount="1" TargetControlID="TextBox1"
ID="AutoCompleteExtender1" runat="server" FirstRowSelected="false">
</asp:AutoCompleteExtender>
</td>
</tr>
</table>
Web.Config
<connectionStrings>
<add name="Default" providerName="System.Data.SqlClient" connectionString="Data Source=SERVERNAME;database=DBNAME;uid=sa;pwd=123;connection reset=false;connection lifetime=1000000;enlist=true;min pool size=1;max pool size=1000000"/>
</connectionStrings>
And Don't Forgot to create table and insert some records in SQL Server

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

I get the following error in a page:
'The name 'DataList1' does not exist in the current context'
Here is my code:
listviewvideo.aspx.cs
private void BindGrid()
{
string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Id, Name from uploadvideo";
cmd.Connection = con;
con.Open();
DataList1.DataSource = cmd.ExecuteReader();
DataList1.DataBind();
con.Close();
}
}
}
listviewvideo.aspx
<table>
<tr>
<td>
<ASPNetFlashVideo:FlashVideo ID="FlashVideo1" runat="server" Height="500" Width="1050"></ASPNetFlashVideo:FlashVideo>
<asp:FileUpload ID="FileUpload1" runat="server" CssClass="myButton" />
<asp:Button ID="btnupload" runat="server" Text="Upload" OnClick="btnupload_Click" CssClass="myButton" />
<hr />
<asp:DataList ID="DataList1" Visible="true" runat="server" AutoGenerateColumns="false" RepeatColumns="2" CellSpacing="5">
<ItemTemplate>
<u>
<%# Eval("Name") %>
</u>
<a class="player" style="height:300px; width:300px; display:block" href='<%# Eval("Id","FileCS.ashx?Id={0}") %>'></a>
</ItemTemplate>
</asp:DataList>
</td>
</tr>
</table>
I get the following error in a page:
'The name 'DataList1' does not exist in the current context'
You might get this error. There 3 solutions for this
Save your project and close the Solution, close the IIS Express also. And check whether it works or not.
Try adding the the datalist by writing below code in your listviewvideo.aspx.designer.cs page of where you are adding the Datalist item.
Check your code behind file name and Inherits property on the #Page directive, make sure they both match.
Also you can have a look here for more clear picture
ID Does not exist in the current context
protected global::System.Web.UI.WebControls.DataList Datalist1;
Hope this helps.

Categories