Hi i want to basically insert the values in the labels to a table in ms access.
I have done it for textbox and it stores but for Label When i try to store it no error shows up but it does not store in the database what should i do? I am using the following code
static OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\New folder\Project 1.0\WebSite1\New Microsoft Office Access 2007 Database.accdb");
OleDbDataAdapter ada = new OleDbDataAdapter();
OleDbCommand cmd = new OleDbCommand();
OleDbDataReader dr;
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string str = "insert into Orders (Products, Amount)" + " values (#p1, #p2)";
con.Open();
cmd = new OleDbCommand(str, con);
cmd.Parameters.AddWithValue("#p1", Label18.Text);
cmd.Parameters.AddWithValue("#p2", Label16.Text);
cmd.ExecuteNonQuery();
con.Close();
}
catch
{
Console.WriteLine("Exception Occured");
}
finally
{
if (con != null && con.State != ConnectionState.Closed)
{ con.Close(); }
}
}
Also i tried storing textbox value into the same Table "Orders" under the column "Address" but facing the same above issue...The table does not update. I have used this code before for other textboxes etc for different tables and it has worked fine..
static OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\New folder\Project 1.0\WebSite1\New Microsoft Office Access 2007 Database.accdb");
OleDbDataAdapter ada = new OleDbDataAdapter();
OleDbCommand cmd = new OleDbCommand();
OleDbDataReader dr;
protected void Button1_Click(object sender, EventArgs e)
{
{
string str = "insert into Orders (Address)" + " values (#p1)";
con.Open();
cmd = new OleDbCommand(str, con);
cmd.Parameters.AddWithValue("#p1", TextBox1.Text);
cmd.ExecuteNonQuery();
con.Close();
}
}
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement
try with
string str = "insert into Orders (Products, Amount) values (?,?)";
You can change the code as below
protected void Button1_Click(object sender, EventArgs e)
{
try
{
using (OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\New folder\Project 1.0\WebSite1\New Microsoft Office Access 2007 Database.accdb"))
using (OleDbCommand cmd = new OleDbCommand("insert into Orders (Products, Amount) values (?,?)", con))
{
cmd.Parameters.AddWithValue("#p1", Label18.Text);
cmd.Parameters.AddWithValue("#p2", int.Parse(Label16.Text));
con.Open();
int no = cmd.ExecuteNonQuery();
Console.WriteLine("number of rows affected = " + no);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception Occured :" ex.ToString());
}
}
Related
Query with parameters works perfectly in ms access database. But when I supply the same parameters from C# winforms application it returns no records.
If the parameter is passed to the query then it will use that parameter in where clause, otherwise it will retrieve all records.
bus table sample data:
Ms-Access Query:
PARAMETERS parPlateNo Text ( 255 );
SELECT bus.*
FROM bus
WHERE (((bus.plateNo) Like IIf(IsNull([parPlateNo]), True ,"%" & [parPlateNo] & "%")));
C# Code:
using (OleDbConnection conn = new OleDbConnection(myGlobals.connString))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter())
{
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "qryBus";
if(plateNo == "")
cmd.Parameters.AddWithValue("?", DBNull.Value);
else
cmd.Parameters.AddWithValue("?", plateNo);
adapter.SelectCommand = cmd;
dsDetails = new DataSet();
adapter.Fill(dsDetails, "details");
}
}
}
PlateNo is a text column.
Remarks: If I remove the like statement in ms access query and run the same code in C#, it will run perfectly and retrieve all the records in table.
After that, I display the data in datagridview using bindingsource.
Why this is happening?
You using oleDB. You have to change that query and use % as wild cards. DAO, and native Access you use *, but for ADO, or oleDB, you have to use % as the wild cards.
Here are a couple of examples that should help you get this up and running.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Server=Your_Server_Name;Database=AdventureWorksLT2012;Trusted_Connection=True");
try
{
cmd = new SqlCommand("insert into [dbo].[Student] values(#a,#b,#c)", con);
cmd.Parameters.AddWithValue("#a", int.Parse(textBox1.Text));
cmd.Parameters.AddWithValue("#b", textBox2.Text);
cmd.Parameters.AddWithValue("#c", textBox3.Text);
con.Open();
a = cmd.ExecuteNonQuery();
if (a > 0)
{
MessageBox.Show("Data Submited");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
AND
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Server=Your_Server_Name;Database=AdventureWorksLT2012;Trusted_Connection=True");
try
{
cmd = new SqlCommand("select * from student where sid=#a", con);
cmd.Parameters.AddWithValue("#a",int.Parse(comboBox1.SelectedItem.ToString()));
con.Open();
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
if (dr.Read())
{
textBox1.Text = dr["sid"].ToString();
textBox2.Text = dr["fname"].ToString();
textBox3.Text = dr["lname"].ToString();
//label1.Text = dr["cdate"].ToString();
}
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
private void Delete_Click(object sender, EventArgs e)
{
//i have used this query for delete button
DataSet ds = new DataSet();
OleDbDataAdapter ad = new OleDbDataAdapter();
OleDbConnection con = new
OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\Users\HP\Desktop\sd.mdb");
con.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\Users\HP\Desktop\sd.mdb";
con.Open();
//this is the query i have used
OleDbCommand cmd = new OleDbCommand("DELETE FROM car_model WHERE Description ='" + des+ "'", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Deleted");
con.Close();
}
//i have table named:car_model & attribute as Description
Your quotes don't look right, but my eyes are not great and anyway, the compiler would pick that up immediately, so I guess it's something else.
private void BtnDelete_Click(object sender, RoutedEventArgs e)
{
DataRowView drv = (DataRowView)dataGridView1.SelectedItem;
int id = drv.Row[0];
if(drv != null)
{
delete(id);
}
}
public void delete(int id)
{
try
{
con.Open();
OleDbCommand comm = new OleDbCommand("Delete From Car_Model Where Description = #Des", con);
comm.Parameters.AddWithValue("#Des", id);
comm.ExecuteNonQuery();
}
catch(OleDbException ex)
{
MessageBox.Show("DataConnection not found!", ex);
}
finally
{
con.Close();
}
Also, use the '#' character to prevent SQL Injection issues. I don't think this is necessarily a problem with MS Access, but it's a good habit to get into.
https://www.w3schools.com/sql/sql_injection.asp
public string ss = "Data Source=D\\SQLEXPRESS;Initial Catalog=gym;Integrated Security=True";
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
string q2 = "insert into gym.dbo.customer (name, weight, height, add_class, gender, fees) values ('" + this.textBox1.Text + "','" + this.textBox2.Text + "','" + this.textBox3.Text + "','" + this.comboBox1.Text + "','" + this.comboBox2.Text + "','" + this.comboBox3.Text + " ') ;";
SqlConnection con = new SqlConnection(ss);
SqlCommand cmd = new SqlCommand(q2, con);
SqlDataReader read;
try
{
con.Open();
read = cmd.ExecuteReader();
MessageBox.Show("Welcome to our gym");
while (read.Read()) { };
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
How can I insert and save data into the database using Visual Studio and C#?
This code throws an error. Anyone please give the suggestion to me to solve the error.
image description
At first make sure your the data type of different column of customer table.
Then make sure what type of data you have to save for combobox.
you have to get the selected value from your Combobox. combobox1,combobox2,combobox3 retuns only the class name
System.Windows.Forms.ComboBox
Besides others, it is recommended to use parameter .. like this:
You can follow this example
private void button1_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\abdul samad\documents\visual studio 2013\Projects\newpro\newpro\Database1.mdf;Integrated Security=True"))
{
try
{
using (var cmd = new SqlCommand("INSERT INTO registor (Name, FullName, Password, Email, Gander) VALUES (#Name,#Fullname,#Password,#Email, #Gander)"))
{
cmd.Connection = con;
cmd.Parameters.Add("#Name", txtfname.Text);
cmd.Parameters.Add("#Fullname", txtfname.Text);
cmd.Parameters.Add("#Password", txtpass.Text);
cmd.Parameters.Add("#Email", txtemail.Text);
cmd.Parameters.Add("#Gander", comboBox1.GetItemText(comboBox1.SelectedItem));
con.Open()
if(cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
}
}
catch (Exception e)
{
MessageBox.Show("Error during insert: " + e.Message);
}
}
}
The comments are getting a bit busy, so this is the sort of thing you need to do (including parameterising the query):
Specifically, you don't need a reader for an insert statement as it doesn't return a result set.
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
var sql = "insert into dbo.customer ...";
using (var con = new SqlConnection(ss))
{
var cmd = new SqlCommand(sql , con);
con.Open();
cmd.ExecuteScalar();
MessageBox.Show("Welcome to our gym");
}
}
Hi check that customer table is available in gym Database.
else try this link
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into customer (name,weight,height,add_class,gender,fees) values(#name,#weight,#height,#add_class,#gender,#fees)", con);
cmd.Parameters.AddWithValue("name", this.textBox1.Text);
if (con.State == ConnectionState.Closed)
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
I found that your connection string declaration is wrong
public string ss = "Data Source=D\\SQLEXPRESS;Initial Catalog=gym;Integrated Security=True";
need to update like below
public string ss = "Data Source=abc\\SQLEXPRESS;Initial Catalog=gym; user id=sa; Password=123456";
Data source will be not be D, It should be Server name.
enter image description here
I have two tables in a SQL Server database. I select from table ADMS and I need to insert master table by gridview but I dont know how to insert with gridview. Please help. I've tried for many days and I did not pass yet
protected void Button3_Click1(object sender, EventArgs e)
{
if (RadioButton2.Checked)
{
SqlConnection con = new SqlConnection(MyConnectionString);
// con.Open(); // don't need the Open, the Fill will open and close the connection automatically
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM ADMS_Machining where datetime='" + TextBox1.Text + "'", con);
mytable = new DataTable();
da.Fill(mytable);
GridView2.DataSource = mytable;
GridView2.DataBind();
}
else
{
SqlConnection con = new SqlConnection(MyConnectionString);
// con.Open(); // don't need the Open, the Fill will open and close the connection automatically
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Machining_Master where datetime='" + TextBox1.Text + "'", con);
mytable = new DataTable();
da.Fill(mytable);
GridView2.DataSource = mytable;
GridView2.DataBind();
}
}
protected void Button4_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
String strConnString, strSQL;
strConnString = "Server=kane-pc;UID=sa;PASSWORD=1234;Database=Machining;Max Pool Size=400;Connect Timeout=600;";
//here
conn.ConnectionString = conn;
conn.Open();
cmd.Connection = conn;
cmd.CommandText = strSQL;
}
You can extract values from a grid view depending on what you have placed in the cells...
string value = this.GridView2.Rows[0].Cells[0].Text;
You can also track the selected row event, and get specific controls like the following...
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
string someValueTakenFromLabel = (GridView2.SelectedRow.FindControl("lblAnyLabelHere") as Label).Text;
// .... do something with value here
}
I suggest you go through some tutorials though to get the hang of how to use GridView.
http://www.asp.net/web-forms/videos/building-20-applications/lesson-8-working-with-the-gridview-and-formview
http://www.aspsnippets.com/Articles/How-to-get-Selected-Row-cell-value-from-GridView-in-ASPNet.aspx
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview%28v=vs.110%29.aspx
You have to first read data from cells and then insert them into database using SqlCommand.
Assuming that you have M_ID and M_NAME columns in your Machining_Master table you can insert values to database as below:
//Assuming that your id column is first column and name is second column
//get value of id and name
int mId = Convert.ToInt32(GridView2.SelectedRow.Cells[0].Text);
string mName = GridView2.SelectedRow.Cells[1].Text;
string connectionStrng = "your connection string";
string insertSql = "INSERT INTO Machining_Master (M_ID, M_NAME) VALUES (#mId, #mName)";
using (SqlConnection conn = new SqlConnection(connectionStrng))
{
using (SqlCommand cmd = new SqlCommand(insertSql, conn))
{
try
{
cmd.Parameters.Add(new SqlParameter("mId", mId));
cmd.Parameters.Add(new SqlParameter("mName", mName));
conn.Open();
cmd.ExecuteNonQuery();
}
finally
{
//Close connection
conn.Close();
}
}
}
How to add data into Specified columns in mysql database table using c# button click, once i clicked the button it will be passing to the catch
here is my add button code
private void Button_add_Click(object sender, RoutedEventArgs e)
{
try
{
string Query = #"INSERT INTO `bcasdb`.`tbl_department`(
`dep_id`,
`dep_name`,
`tbl_branch_branch_id`)
VALUES ("
+ this.depIDInput.Text + ",'"
+ this.depnameInput.Text + "','"
+ this.dep_branchIDInput.Text + "')";
//This is command class which will handle the query and connection object.
MySqlConnection conn = new MySqlConnection(BCASApp.DataModel.DB_CON.connection);
MySqlCommand cmd = new MySqlCommand(Query, conn);
MySqlDataReader MyReader;
conn.Open();
MyReader = cmd.ExecuteReader();// Here our query will be executed and data saved into the database.
conn.Close();
successmsgBox();
}
catch (Exception)
{
errormsgBox();
}
}
here is all the columns of the table,
INSERT INTO `bcasdb`.`tbl_student`
(`reg_id`,
`std_fname`,
`std_lname`,
`tbl_batch_batch_id`,
`gender`,
`dob`,
`email`,
`mobile`,
`contact_address`,
`home_address`,
`status`,
`course_id`,
`depart_id`,
`parent_name`,
`telephone`,
`nationality`,
`nic`,
`passport_no`,
`acadamic_qulification`,
`current_employement`,
`gce_ol`,
`gce_al`,
`birth_certifiacte`,
`copy_of_nic`,
`police_clerence`,
`tbl_studentcol`)
VALUES
I believe your code should be rewritten as following:
private void Button_add_Click(object sender, RoutedEventArgs e)
{
try
{
string Query = #"INSERT INTO `bcasdb`.`tbl_department`(
`dep_id`,
`dep_name`,
`tbl_branch_branch_id`)
VALUES (#depId, #depName, #branchId)";
//This is command class which will handle the query and connection object.
using (MySqlConnection conn = new MySqlConnection(BCASApp.DataModel.DB_CON.connection))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand(Query, conn))
{
cmd.Parameters.Add("#depId", this.depIDInput.Text);
cmd.Parameters.Add("#dep_name", this.depnameInput.Text);
cmd.Parameters.Add("#branchId", this.dep_branchIDInput.Text);
cmd.ExecuteNonQuery();
}
}
successmsgBox();
}
catch (Exception)
{
errormsgBox();
}
}