I'm brand new to c# and am trying to figure out the delete and update portion of my table. I get the insert portion because I am not trying to select anything in my table prior to clicking a button. With the delete and update however, I am confused as to how a query pairs up to the selected row in my table. If anyone could point me in the right direction that would be great. I am using a dataset and GridControl in devexpress. I also have to make use of buttons to perform the events and will not be using the command fields within the grid. And I'm working on making my insert with parameters.
My list:
public partial class PatientList : XtraForm
{
public PatientList()
{
InitializeComponent();
}
private void PatientList_Load(object sender, EventArgs e)
{
SAConnection conn = new SAConnection("dsn={SQL Anywhere 10};uid=dba;pwd=sql;databasefile=C:\\Users\\Kbaker1\\Desktop\\Training1.db;");
SADataReader rdr = null;
string Query = "SELECT * FROM patient";
SADataAdapter da = new SADataAdapter(Query, conn);
DataSet ds = new DataSet();
da.Fill(ds);
grdList.DataSource = ds.Tables[0];
try
{
conn.Open();
SACommand cmd = new SACommand(Query, conn);
rdr = cmd.ExecuteReader();
}
finally
{
if (rdr != null)
{
rdr.Close();
}
if (conn != null)
{
conn.Close();
}
}
}
private void btnNewPatient_Click(object sender, EventArgs e)
{
Edit editPat = new Edit();
editPat.Show();
}
private void btnEditPatient_Click(object sender, EventArgs e)
{
Edit editPat = new Edit();
editPat.Show();
}
private void btnDeletePatient_Click(object sender, EventArgs e)
{
PatientService ps = new PatientService();
ps.DeletePatient();
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}
The service class performing the operations:
public class PatientService
{
public void DataAccess()
{
}
public void CreatePatient(Patient patient)
{
SAConnection conn = new SAConnection();
SACommand cmd = new SACommand();
conn.ConnectionString = ("dsn={SQL Anywhere 10};uid=dba;pwd=sql;DBF=C:\\Users\\Kbaker1\\Desktop\\Training1.db;");
conn.Open();
cmd.Connection = conn;
cmd.CommandText = (#"INSERT INTO patient (patient_id, first_name, last_name, address, city, state, zipcode, phone, classification_id)
VALUES ('"
+ patient.PatientID + "','"
+ patient.FirstName + "','"
+ patient.LastName + "','"
+ patient.Address + "','"
+ patient.City + "','"
+ patient.State + "','"
+ patient.ZipCode + "','"
+ patient.Phone + "','"
+ patient.ClassificationID + "'); ");
cmd.ExecuteNonQuery();
conn.Close();
}
public void UpdatePatient()
{
}
public void DeletePatient()
{
SAConnection conn = new SAConnection();
conn.ConnectionString = ("dsn={SQL Anywhere 10};uid=dba;pwd=sql;DBF=C:\\Users\\Kbaker1\\Desktop\\Training1.db;");
conn.Open();
SACommand cmd = new SACommand("DELETE FROM patient WHERE patient_id = #patient_id");
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
}
}
Just replace the INSERT sql statement with UPDATE
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
Delete:
DELETE FROM table_name
WHERE some_column=some_value;
Related
I'm trying to update the selected row in access database. How do I Update selected row in my access database?
I've tried using the update command
private void btnCancel_Click(object sender, EventArgs e)
{
try
{
for (int i = 0; i < dataRes.Rows.Count; i++)
{
string a = "Cancelled";
DataGridViewRow dr = dataRes.Rows[i];
if (dr.Selected == true)
{
connection.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;
cmd.CommandText = "UPDATE Reservation SET Status ='" + a + "' WHERE ID = " + i +" ";
cmd.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Reservation Cancelled");
}
}
}
I am making a school project and i need to put text input (name and gender) into a database. This database (the names and genders) then have to be shown in a listbox. The code i have at the moment is put below, how can i make it work? Thanks in advance!
private void Form1_Load(object sender, EventArgs e)
{
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM
Persoon", connection))
{
connection.Open();
DataTable PersoonTable = new DataTable();
adapter.Fill(PersoonTable);
lb_gebruikers.DisplayMember = "Naam";
lb_gebruikers.ValueMember = "Id";
lb_gebruikers.DataSource = PersoonTable;
}
}
private void button1_Click(object sender, EventArgs e)
{
string naam = tb_naam.Text;
string geslacht = tb_geslacht.Text;
Persoon nieuwpersoon = new Persoon(naam, geslacht);
personen.Add(nieuwpersoon);
foreach (var Persoon in personen)
{
lb_gebruikers.Items.Add("Naam: " + nieuwpersoon.Naam +
"Geslacht: " + nieuwpersoon.Geslacht);
}
}
As i understand you just have to add a insert between button1.click and addToList process.
private void btnSave_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection("Server =.;Database=People; Integrated Security = true");
con.Open();
SqlCommand cmd = new SqlCommand(); // you can define commandText and connection in SqlCommand(defineArea);
cmd.Connection = con; // like; cmd = newSqlCommand("Insert into...",con);
string name = txtName.Text;
string gender = txtGender.Text;
cmd.CommandText = "Insert into Person(Name,Gender)values('" + name + "','" + gender + "')";
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
lstBxPerson.Items.Add(name + " - " + gender);
MessageBox.Show("Save Success!");
}
catch (Exception ex)
{
MessageBox.Show("Exception : "+ex);
}
}
Database Name : People
Table Name : Person
All Parts Image :
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 want it to show the selected value from the drop down list and show it on gridview. It is supposed to query from the database using Where to indicate the selected value to show. For example, I select james from the drop down list. It supposes to go to the database and query james row. After that the grid view is supposed to show only one value which james. But now I am having a problem where the grid view show every data that is available in the database.
public partial class Search_Engine : System.Web.UI.Page
{
#region Database
static string HostName = "localhost";
static string DatabaseName = "finalproject";
static string TableName = "truckinfo";
//static string TableBucket = "bucketbrigade";
static string UserName = "root";
static string Password = "";
//--- Used for access to database infomation-----
string ConnStr = "Data Source=" + HostName + ";" +
"Database=" + DatabaseName + ";" +
"User ID=" + UserName + ";" +
"Password=" + Password;
string Qry = "";
MySqlConnection Con;
MySqlCommand Cmd;
MySqlDataReader Rdr;
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
using (Con = new MySqlConnection(ConnStr))
{
Con.Open();
using (Cmd = new MySqlCommand("SELECT * FROM truckinfo", Con))
{
using (Rdr = Cmd.ExecuteReader())
{
if (Rdr.HasRows)
{
DropDownList1.DataSource = Rdr;
DropDownList1.DataValueField = "truckplateno";
DropDownList1.DataTextField = "truckplateno";
DropDownList1.DataBind();
}
}
}
}
}
}
private void BindData()
{
DataTable dt = new DataTable();
try
{
MySqlConnection Con = new MySqlConnection(ConnStr);
Con.Open();
MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM " +
DatabaseName + "." + TableName , Con);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
Con.Close();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Con = new MySqlConnection(ConnStr);
Con.Open();
try
{
String getquery;
// String a;
getquery = DropDownList1.Text;
TextBox1.Text = getquery;
// a = TextBox2.Text;
// TextBox1.Text = a;
Qry = #"SELECT * FROM finalproject.truckinfo WHERE truckplateno=" + "'" + getquery + "'" + ";";
Cmd = new MySqlCommand(Qry, Con);
Cmd.ExecuteNonQuery();
Con.Close();
BindData();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
}
You need to get the selected value using SelectedValue of dropdownlist and then query database using this value.
getquery = DropDownList1.SelectedValue;
Also you are using BindData method which will always select all data from database you need to seprate this method so only selected data is bind to gridview.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
String getquery;
getquery = DropDownList1.Text;
MySqlConnection Con = new MySqlConnection(ConnStr);
Con.Open();
MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM finalproject.truckinfo WHERE truckplateno='" + getquery + "'", Con);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
Con.Close();
}
You are calling ExecuteNonQuey function which is used to Insert or Update data in database so it will not return any data.
Also when using SqlDataAdapter you don't need to explicitly call
Open and Close function for opening and closing connection.
Change your DropDownlist_SelectedIndexChanged function to the following:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Con = new MySqlConnection(ConnStr);
DataTable dt = new DataTable();
try
{
Con.Open();
string getquery = DropDownList1.SelectedValue;
TextBox1.Text = getquery;
// a = TextBox2.Text;
// TextBox1.Text = a;
Qry = #"SELECT * FROM finalproject.truckinfo WHERE truckplateno=" + "'" + getquery + "'" + ";";
MySqlCommand ddlCMD = new MySqlCommand(Qry, Con);
MySqlDataAdapter msda = new MySqlDataAdapter(ddlCMD);
msda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
finally{
Con.Close();
}
}
I wonder how to set The Picture box, and it will display 2 Images. On Value True image number 1, on value False, image number 2. I'm a noob in programming... My Record name is "oddal" dataType is "bit"
Here is my Code
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\MSI\Documents\Visual Studio 2010\Projects\Baza z własnymi batonami\Baza z własnymi batonami\Database1.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmd.Connection = cn;
pokazliste();
}
private void button1_Click(object sender, EventArgs e)
{
if (textid.Text != "" & textimie.Text != "")
{
cn.Open();
cmd.CommandText = "Insert into Table1 (id,imie) values('" + textid.Text + "','" + textimie.Text + "')";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Wpis Wprowadzony","Vindykacja by Brzoska");
cn.Close();
textid.Text = "";
textimie.Text = "";
pokazliste();
}
}
private void pokazliste()
{
listBox1.Items.Clear();
listBox2.Items.Clear();
cn.Open();
cmd.CommandText = "Select * From Table1";
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while(dr.Read())
{
listBox1.Items.Add(dr[0].ToString());
listBox2.Items.Add(dr[1].ToString());
}
}
cn.Close();
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox l = sender as ListBox;
if (l.SelectedIndex != -1)
{
listBox1.SelectedIndex = l.SelectedIndex;
listBox2.SelectedIndex = l.SelectedIndex;
textid.Text = listBox1.SelectedItem.ToString();
textimie.Text = listBox2.SelectedItem.ToString();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (textid.Text != "" & textimie.Text != "" & listBox1.SelectedIndex!=-1 )
{
cn.Open();
cmd.CommandText = "delete from Table1 where id='" + listBox1.SelectedItem.ToString() + "' and imie= '" + listBox2.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Wpis Uaktualniony", "Vindykacja by Brzoska");
pokazliste();
textid.Text = "";
textimie.Text = "";
}
}
private void button3_Click(object sender, EventArgs e)
{
if (textid.Text != "" & textimie.Text != "")
{
cn.Open();
cmd.CommandText = "Update Table1 set id='" + textid.Text + "', imie= '" + textimie.Text + "'Where id'" + textid.Text + "'and imie= '" + textimie.Text + "'";
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Wpis Usuniety", "Vindykacja by Brzoska");
pokazliste();
textid.Text = "";
textimie.Text = "";
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
}
}
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\MSI\Documents\Visual Studio 2010\Projects\Baza z własnymi batonami\Baza z własnymi batonami\Database1.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
cn.Open();
cmd.CommandText = "SELECT oddal FROM TableName WHERE (Your = Condition)";
dr = cmd.ExecuteReader();
if dr.Read()
{
if dr("oddal")
{
//Set picture box to image 1
}
else
{ //Set picture box to image 1
}
}
cn.Close();
Make sure to specify your condition in the SELECT. Also, for the future, assign meaningful names to the controls. Instead of button1, say btnInsert...