Insert multiple textbox values into sql database - asp.net

I have 3 textboxes to add Skills, that goes into one column called 'SkillName'.
However, I'm getting this error.
'System.Web.UI.Control' does not contain a definition for 'Text' and no extension method 'Text' accepting a first argument of type 'System.Web.UI.Control' could be found (are you missing a using directive or an assembly reference?)
But I have used the assembly using System.Web.UI.WebControls;
This is my code to add textboxes-
public void InsertSkillInfo()
{
String str = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=DBNAME;Integrated Security=True";
SqlConnection conn = new SqlConnection(str);
try
{
for (int i = 1; i <= 3; i++)
{
conn.Open();
**string skill = (Page.FindControl("TextBox" + i.ToString())).Text;**
const string sqlStatement = "INSERT INTO Cert (SkillName) VALUES (#SkillName)";
SqlCommand cmd = new SqlCommand(sqlStatement, conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters["#SkillName"].Value = skill;
cmd.ExecuteNonQuery();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}

Page.FindControl will return a Control, but you want a textbox. If you are sure that the control it finds will always be a textbox, then cast it to a textbox.
Either:
string skill = (TextBox)((Page.FindControl("TextBox" + i.ToString()))).Text;
or
var skill = "";
var control = Page.FindControl("TextBox" + i.ToString()) as TextBox;
if(control != null {
skill = control.Text;
}

You need to cast the control to a TexBox so it should be this
string skill = ((TextBox) Page.FindControl("TextBox" + i.ToString())).Text;

You can Try it simply like this
string skill = ((TextBox)(Page.FindControl("TextBox" + i.ToString()))).Text;

Related

Can't update access database threw asp.net

my access database wont update with this code. what seems to be the problem?
i have tried a lot of methods for updating my access database with no sucsess
please guys some help.
protected void Btnupdate_Click(object sender, EventArgs e)
{
foreach (RepeaterItem RI in rptEdit.Items)
{
Label id = RI.FindControl("Pid") as Label;
TextBox prdname = RI.FindControl("prdname") as TextBox;
TextBox prdprice = RI.FindControl("prdprice") as TextBox;
TextBox prdshortdesc = RI.FindControl("prdshortdesc") as TextBox;
TextBox prdtype = RI.FindControl("prdtype") as TextBox;
TextBox prdbrand = RI.FindControl("prdbrand") as TextBox;
int updated;
string connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Table.accdb";
using (var conn = new OleDbConnection(connection))
{
conn.Open();
string updSql = #"UPDATE ProductList SET
Pname = '" + prdname.Text + "' WHERE Pid = ?";
using (var cmd = new OleDbCommand(updSql, conn))
{
cmd.Parameters.Add("#Pname", OleDbType.VarChar).Value = prdname.Text;
updated = cmd.ExecuteNonQuery();
conn.Dispose();
conn.Close();
}
}
}
}
Just use the ? style parameters in your SQL.
string sql = #"UPDATE ProductList SET Pname = ? WHERE Pid = ?";
Then just make sure you add your parameters in the same order in your code that they appear in the SQL.
cmd.Parameters.Add(prdName.Text);
cmd.Parameters.Add(int.Parse(id.Text));
You need to make sure the type of the variable being added in C# matches the type in the DB (in terms of text or number). Then it can be properly quoted or not as needed.

Incorrect syntax near the keyword 'and'

I am trying to filter the gridview with the help of a few checkboxlists and it works absolutely fine.It is all real time since i am using a update panel.Now when i try to add one more filer i.e couple of datepickers to filter the gridview depending on the two dates,it gives me the error message " Incorrect syntax near the keyword 'and'.". The entire code is given below :
private void BindGrid()
{
string CS = ConfigurationManager.ConnectionStrings["SportsActiveConnectionString"].ConnectionString;
string query = "Select * from tblAllEvents";
string condition = string.Empty;
string conditionDisability = string.Empty;
string conditionDates = string.Empty;
foreach (ListItem item in cblGender.Items)
{
condition += item.Selected ? string.Format("'{0}',", item.Value) : string.Empty;
}
if (!string.IsNullOrEmpty(condition))
{
condition = string.Format(" Where Gender IN ({0})", condition.Substring(0, condition.Length - 1));
}
else
{
condition = string.Format(" Where Gender IN ('Male','Female','Mixed')", condition.Substring(0,Math.Max(0,condition.Length - 1)));
}
foreach (ListItem item in cblDisability.Items)
{
conditionDisability += item.Selected ? string.Format("'{0}',", item.Value) : string.Empty;
}
if (!string.IsNullOrEmpty(conditionDisability))
{
conditionDisability = string.Format(" and Disabled IN ({0})", conditionDisability.Substring(0, conditionDisability.Length - 1));
}
if(txtEventStart.Text == null)
{
txtEventStart.Text = "01/01/1900";
}
if(txtEventEnd.Text == null)
{
txtEventEnd.Text = "01/01/2050";
}
conditionDates = string.Format(" and EventStart between {0} and {1}",txtEventStart.Text,txtEventEnd.Text);
using (SqlConnection con = new SqlConnection(CS))
{
using (SqlCommand cmd = new SqlCommand(query + condition + conditionDisability + conditionDates))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
cmd.Connection = con;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
Please note the problem arises on when i include 'conditionDates' in the query. What can be the other ways to make the query work.
Edit : As i said earlier, the problem lies in the below code
if(txtEventStart.Text == null)
{
txtEventStart.Text = "01/01/1900";
}
if(txtEventEnd.Text == null)
{
txtEventEnd.Text = "01/01/2050";
}
conditionDates = string.Format(" and EventStart between {0} and {1}",txtEventStart.Text,txtEventEnd.Text);
You are missing apostrophes around the values:
conditionDates = string.Format(" and EventStart between '{0}' and '{1}'", txtEventStart.Text, txtEventEnd.Text);
Note however that code like this is wide open for SQL injection attacks. You should use parameters in the query instead:
conditionDates = " and EventStart between #EventStart and #EventEnd";
Then you add parameters to the command object parameter collection to supply the values to the query:
cmd.Parameters.Add("#EventStart", SqlDbType.DateTime).Value = txtEventStart.Text;
cmd.Parameters.Add("#EventEnd", SqlDbType.DateTime).Value = txtEventEnd.Text;
You clearly have a SQL syntax error. First debug your code and get the resulting query and run it separately in SQL Server. You will inspect it better in that way.
It's about how you are concatenating the SQL query when you add that part.

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack when I use scope identity

Here is ehat I try to do
on button_click I read the values from the text boxes and insert them in them in the database.
as tourist number for example maybe two or three tourists with ExecuteScalar; i get the ids of teh tourists which are inserted!
public void cmdInsert_OnClick(object sender, EventArgs e)
{
if (Page.IsValid)
{
string numtourist = (string)Session["tourist_number"];
for (int i = 0; i < Int32.Parse(numtourist); i++)
{
TextBox tx888 = (TextBox)FindControl("txtNameK" + i.ToString());
TextBox tx888_1 = (TextBox)FindControl("txtMidNameK" + i.ToString());
TextBox tx888_2 = (TextBox)FindControl("txtLastNameK" + i.ToString());
string insertSQL = "INSERT INTO Tourist (Excursion_ID, Excursion_date_ID, Name_kir,Midname_kir, Lastname_kir)";
insertSQL += " VALUES (#Excursion_ID, #Excursion_date_ID, #Name_kir,#Midname_kir, #Lastname_kir) SELECT ##IDENTITY";
string connectionString = "Data Source = localhost\\SQLExpress;Initial Catalog=excursion;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(insertSQL, con);
cmd.Parameters.AddWithValue("#Excursion_ID", Convert.ToInt32(mynew2));
cmd.Parameters.AddWithValue("#Excursion_date_ID", Convert.ToInt32(mynewnewstring));
cmd.Parameters.AddWithValue("#Name_kir", tx888.Text);
cmd.Parameters.AddWithValue("#MidName_kir", tx888_1.Text);
cmd.Parameters.AddWithValue("#LastName_kir", tx888_2.Text);
int added;
try
{
con.Open();
added = (int)cmd.ExecuteScalar();
lblproba.Text = "";
Tourist.Add(added);
lblproba.Text += Tourist.Count();
}
catch (Exception ex)
{
lblproba.Text += ex.Message;
}
finally
{
con.Close();
}
}
createReservation();
}
}
I call CreateReservationFunction AND i CREATE A NEW RESERVAION WITH THE ID OF THE USER WHO HAS MADE THE RESERVATION. wITH SELECT IDENTITY I TRY TO GET THE RESERVATION_ID of the reservation and here I get the exception "Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack". So I wonder can this exception has something commn with the fact that in my solution exceptthe asp.net web projectI got library class in which I has .edmx file The entity framework model of my database and in my last form I don't use Ado,net but Entity framework
public void createReservation()
{
string insertSQL = "Insert INTO RESERVATIONS (User_ID) values (#User_ID) SELECT ##IDENTITY";
string connectionString = "Data Source = localhost\\SQLExpress;Initial Catalog=excursion;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(insertSQL, con);
cmd.Parameters.AddWithValue("#User_ID", 9);
try
{
con.Open();
string added = cmd.ExecuteScalar().ToString();
createTouristReservation(added);
}
catch (Exception ex)
{
lblproba.Text+= ex.Message;
}
}
Don't use ##IDENTITY but SCOPE_IDENTITY and add a semicolon between the insert and the select.
string insertSQL = #"INSERT INTO Tourist (Excursion_ID, Excursion_date_ID, Name_kir,Midname_kir, Lastname_kir)
VALUES (#Excursion_ID, #Excursion_date_ID, #Name_kir,#Midname_kir, #Lastname_kir)
;SELECT CAST(scope_identity() AS int)";

Update in GridView "No value given for one or more parameters"

I have this code (below) and I am getting the following error:
No value given for one or more parameters
But when it is run again, values are shown updated for 'RateCenterName', 'QuantityThreshold', 'RateCenterID' but not for 'Province'
The code:
string updateSql = "UPDATE RateCenters SET RateCenterName = ?, Province=?, QuantityThreshold = ?" + " WHERE RateCenterID= ?";
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
DropDownList ddl = (DropDownList)row.FindControl("DropDownList2"); // assigning the dropdownlist item to 'ddl'
TextBox rateCenterName = (TextBox)row.FindControl("txtRateCenterName"); // assigning textbox input item
TextBox quantityThreshold = (TextBox)row.FindControl("txtQuantityThreshold"); // assigning textbox input item
Label ratecenterid = (Label)row.FindControl("Label1"); // assigning the label value
//OleDbConnection conn = new OleDbConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ToString());
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\arjun.giridhar\My Documents\Visual Studio 2010\Projects\BillingApplicationNew\BillingApplicationNew\App_Data\db1.mdb;Persist Security Info=False");
OleDbCommand cmd = null;
try
{
cmd = new OleDbCommand(updateSql, conn);
cmd.Parameters.Add("#RateCenterName", OleDbType.VarChar).Value = rateCenterName.Text;
cmd.Parameters.Add("#Province", OleDbType.VarChar).Value = ddl.SelectedItem.Text;
cmd.Parameters.Add("#QuantityThreshold", OleDbType.Integer).Value = Convert.ToUInt32(quantityThreshold.Text);
cmd.Parameters.Add("#RateCenterID", OleDbType.Integer).Value = Convert.ToInt32(ratecenterid.Text);
conn.Open();
cmd.Connection = conn;
cmd.ExecuteNonQuery();
//GridView1.EditIndex = -1; //refreshing
//GridView1.DataBind();
}
catch (OleDbException ex)
{
throw (ex);
}
finally
{
conn.Close();
conn.Dispose();
}
}
Can anyone see what's wrong?
Moderator edit:
He solved the problem, but his solution is deep inside one of the comment threads:
I got it, i removed the Row updating event and just tried it once
again without adding that event.
I think he means: he took this code out of the RowUpdating event handler and put it elsewhere.
there might be Problem in your code because you are trying to edit access database and you are writing code of sqldatabase....
You Update Statement code
string updateSql = "UPDATE RateCenters SET RateCenterName =?, Province=? ,
QuantityThreshold = ? WHERE RateCenterID= ?";
using (OleDbConnection con = new OleDbConnection(scon))
{
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("RateCenterName", str2);
cmd.Parameters.AddWithValue("Province", str3);
cmd.Parameters.AddWithValue("QuantityThreshold ", str4);
cmd.Parameters.AddWithValue("RateCenterID", str5);
con.Open();
cmd.ExecuteNonQuery();
}
}
You have a missing space before WHERE when you are building your SQL.
Line 2 in your sample code.
"WHERE RateCenterID= #RateCenterID"; // this the error. you need to provide space before where
you need to add space before Where .
this you should try
string updateSql = "UPDATE RateCenters SET RateCenterName = #RateCenterName, Province=
#Province, QuantityThreshold = #QuantityThreshold" + " WHERE RateCenterID= #RateCenterID";
The most likely problem is passing a null value to either RateCenterName or Province.
What happens when you try this:
cmd.Parameters.Add("#RateCenterName", OleDbType.VarChar).Value = "rateCenter";
cmd.Parameters.Add("#Province", OleDbType.VarChar).Value = "ddl";
cmd.Parameters.Add("#QuantityThreshold", OleDbType.Integer).Value = 0;
cmd.Parameters.Add("#RateCenterID", OleDbType.Integer).Value = 1;

ASP.Net insert data from form to a database Exception

I'm trying to insert data from a form to my database and it is throwing this error:
No mapping exists from object type System.Web.UI.WebControls.TextBox to a known managed provider native type.
Maybe it has to do with the fact that I try to get a data from a dropdownlist and I'm not really sure the syntax is great.
Here is the code:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Movie;Integrated Security=True");
conn.Open();
string titleName = Title.Text;
string sqlQuery = ("INSERT INTO Movies(Ganere, Title, Descreption) VALUES (#Ganere, #Title , #Descreption) ");
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.Parameters.AddWithValue("Title", Title);
string genre = GenreDropDown.SelectedIndex.ToString();
cmd.Parameters.AddWithValue("Ganere", GenreDropDown);
string descp = Descreption.Text;
cmd.Parameters.AddWithValue("Descreption", Descreption);
if (titleName == null || genre == null)
{
ErrorMessege.Text = "Please fill all of the fields.";
}
else
{
ErrorMessege.Text = "You have successfully add a movie!";
cmd.ExecuteNonQuery();
}
conn.Close();
}
You -weren't using any of the vars where you had the values
string titleName = Title.Text;
string sqlQuery = ("INSERT INTO Movies(Ganere, Title, Descreption) VALUES (#Ganere, #Title , #Descreption) ");
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.Parameters.AddWithValue("Title", titlename);
string genre = GenreDropDown.SelectedIndex.ToString();
cmd.Parameters.AddWithValue("Ganere", genre);
string descp = Descreption.Text;
cmd.Parameters.AddWithValue("Descreption", descp);
if (titleName == null || genre == null)
{
ErrorMessege.Text = "Please fill all of the fields.";
}
else
{
ErrorMessege.Text = "You have successfully add a movie!";
cmd.ExecuteNonQuery();
}
conn.Close();
}
The problem is that you are trying to use the entire textbox as the value to the parameter.
Change:
cmd.Parameters.AddWithValue("Title", Title);
to
cmd.Parameters.AddWithValue("Title", Title.Text);

Resources