I wrote the following program in C#
I have no problem when inserting information in the database
But when deleting information and during debugging, it gets an error on the following
line
cmd.executenonquery();
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace _01_AccessTestDB
{
public partial class frmUser : Form
{
public frmUser()
{
InitializeComponent();
}
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=TestDB.accdb");
OleDbCommand cmd = new OleDbCommand();
void display()
{
DataSet ds = new DataSet();
OleDbDataAdapter adp = new OleDbDataAdapter();
cmd.CommandType = CommandType.Text;
adp.SelectCommand=new OleDbCommand();
adp.SelectCommand.Connection= con;
adp.SelectCommand.CommandText="select * from TBLUser";
adp.Fill(ds, "TBLUser");
dgvUser.DataSource=ds;
dgvUser.DataMember=("TBLUser");
dgvUser.Columns[0].HeaderText="کد";
dgvUser.Columns[1].HeaderText="نام کاربری";
dgvUser.Columns[2].HeaderText="کلمه عبور";
}
private void frmUser_Load(object sender, EventArgs e)
{
display();
}
private void btnSave_Click(object sender, EventArgs e)
{
cmd.Parameters.Clear();
cmd.Connection = con;
con.Open();
cmd.CommandText="insert into TBLUser(ID,UserN,Pass)values(#a,#b,#c)";
cmd.Parameters.AddWithValue("#a", txtCode.Text);
cmd.Parameters.AddWithValue("#b", txtUser.Text);
cmd.Parameters.AddWithValue("#c", txtPass.Text);
cmd.ExecuteNonQuery();
con.Close();
string message, title;
title="تعریف کاربران";
message="اطلاعات جدید با موفقیت ثبت گردید";
MessageBox.Show(message, title, MessageBoxButtons.OK,
MessageBoxIcon.Information);
txtCode.Clear();
txtUser.Clear();
txtPass.Clear();
display();
}
The program is running correctly so far, but it encountered a problem in the data deletion section
private void btnDelet_Click(object sender, EventArgs e)
{
int h = Convert.ToInt32(dgvUser.SelectedCells[0].Value);
cmd.Parameters.Clear();
cmd.Connection=con;
cmd.CommandText="delet from TBLUser Where ID=#N";
cmd.Parameters.AddWithValue("#N", h);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
string message, title;
title="تعریف کاربران";
message="اطلاعات حذف گردید";
MessageBox.Show(message, title, MessageBoxButtons.OK,
MessageBoxIcon.Information);
display();
}
}
}
Change from
cmd.CommandText="delet from TBLUser Where ID=#N";
To
cmd.CommandText="delete from TBLUser Where ID=#N";
Also follow #user18387401 recommendations
In regards to cmd.Parameters.AddWithValue, use cmd.Parameters.Add instead.
Edit
Here is a model to use for removing a record use SQL-Server in .NET Core. Since you are using Access the connection and command change to OleDb. So don't copy-n-paste this code, adapt to your current code. The Remove method should reside in a separate class but can reside in the form.
Best to add in a BindingSource, this way cast someBindingSource.Current to whatever the current row in the DataGridView is e.g. if the source is a DataTable use ((DataRow)someBindingSource.Current).Row.Field... to get the primary key to use for deleting. Once the record is removed use someBindingSource.RemoveCurrent() to remove the record from your DataGridView.
public static (bool success, Exception exception) Remove(int identifier)
{
using var cn = new SqlConnection("TODO");
using var cmd = new SqlCommand
{
Connection = cn,
CommandText = "DELETE FROM TBLUser WHERE Id = #Identifier;"
};
try
{
cn.Open();
cmd.Parameters.Add("#Identifier", SqlDbType.Int).Value = identifier;
cmd.ExecuteNonQuery();
return (true, null);
}
catch (Exception localException)
{
return (false, localException);
}
}
Usage in your form (DataOperations is a separate class)
var (success, exception) = DataOperations.Remove(identifier);
if (success)
{
// record removed
}
else
{
// deal with exception using exception variable
}
Related
im trying to learn c# and sql server and i have some problems with them in n-th layer projects.
so i created a 3-layer project:
1-DataAccessLayer
2-CodeLayer
3-UILayer
i connect all layers with references.
in DataAccessLayer there is a class with this code below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace DataAccessLayer
{
public class DataContent
{
SqlConnection cnn;
SqlCommand cmd;
SqlDataAdapter sa;
DataTable dt;
public DataContent()
{
cnn = new SqlConnection();
cmd = new SqlCommand();
sa = new SqlDataAdapter();
cmd.Connection = cnn;
sa.SelectCommand = cmd;
}
public void connect()
{
cnn.ConnectionString = "Data Source=.;Initial Catalog=testDB;Integrated Security=True";
cnn.Open();
}
public void disConnect()
{
cnn.Close();
}
public void runCommend(string query)
{
cmd.CommandText = query;
cmd.ExecuteNonQuery();
}
public DataTable SELECT(string query)
{
cmd.CommandText = query;
dt = new DataTable();
sa.Fill(dt);
return dt;
}
}
}
in CodeLayer there is a class whit this code below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using DataAccessLayer;
namespace codeLayer
{
public class Data : DataContent
{
public string userName;
public string userPass;
public string uName;
public string uFamily;
public string uTell;
public DataTable validation()
{
base.connect();
string query = "select * from tblData where userName = '{0}' and userPass = '{1}'";
query = String.Format(query, userName, userPass);
DataTable dt = base.SELECT(query);
base.disConnect();
return dt;
}
public void updateTable()
{
base.connect();
string query = "update tblData set userPass = '{0}', uName = N'{1}', uFamily = N'{2}', uTell = '{3}' where userName = '{4}'";
query = String.Format(query, userPass, uName, uFamily, uTell, userName);
base.runCommend(query);
base.disConnect();
}
}
}
my form in UILayer like this:
enter image description here
and i have table with one record that i add manually like this:
enter image description here
and i set all fields in table to not null
there is 2 click event in form:
1-btnSearch_click :
private void btnSearch_Click(object sender, EventArgs e)
{
Data a = new Data();
a.userName = txtUserNameSearch.Text;
a.userPass = txtPassWordSearch.Text;
DataTable newDT = a.validation();
if (newDT != null && newDT.Rows.Count > 0)
{
txtName.Text = newDT.Rows[0]["uName"].ToString();
txtFamily.Text = newDT.Rows[0]["uFamily"].ToString();
txtUserName.Text = newDT.Rows[0]["userName"].ToString();
txtPassWord.Text = newDT.Rows[0]["userPass"].ToString();
txtTell.Text = newDT.Rows[0]["uTell"].ToString();
}
else
{
MessageBox.Show("sorry...! cant finde user with inserted info.", "user not found", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
2-btnEdit_Click:
private void btnEdit_Click(object sender, EventArgs e)
{
Data a = new Data();
a.userName = txtUserName.Text;
a.userPass = txtPassWord.Text;
a.uName = txtName.Text;
a.uFamily = txtFamily.Text;
a.uTell = txtTell.Text;
try
{
a.updateTable();
MessageBox.Show("edit information was success.", "successfull", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch
{
MessageBox.Show("failed to update information", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
so when i run it for test, search function is works and get data from table and puts them in text boxes.
but problem is when i try to edit. after search i clear one of the text boxes and click edit and its just work. Should not i get some exeptions here???
after that i check the table and the field that i cleared before is empty in table like picture below:
enter image description here
whats happning here?? am i doing something wrong?? what did I missed??
please help me to solve this problem.
ps: im sorry for my bad english.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using static System.Data.SqlClient.SqlConnection;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
private SqlCommand cmd;
private Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" && textBox2.Text == "")
{
MessageBox.Show("Please fill up all fields");
}
try
{
SqlCredential Librarypavilion = null;
SqlConnection SqlConnection = new SqlConnection("Data Source=DESKTOP-90R7QPM;Initial Catalog=", Librarypavilion, ";Integrated Security=True");
SqlCommand; cmd = new SqlCommand("select * from login where username = #username and password = #password");
cmd.Parameters.AddWithValue("#username", textBox1.Text);
cmd.Parameters.AddWithValue("#password", textBox2.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
MessageBox.Show(" User is successfully logged in");
}
else
{
MessageBox.Show("Login unsuccessful");
}
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
if (textBox2.Text == "")
{
MessageBox.Show("Please fill up password");
}
}
private void button2_Click(object sender, EventArgs e)
{
Form2 frm2 = new WindowsFormsApp1.Form2();
frm2.Show();
}
}
internal class sqlConnection
{
}
}
I'm quite just learning C# using vs. I am trying to connect the login button into the SQL I created. I can't run the program. it keeps giving me the error
SqlConnection does not contain a constructor that takes 3 arguments.
How do I solve it?
Your primary issue is that your connection string isn't right. It contains spurious ", which makes C# think you have three parameters. There are also other strange syntax errors.
There are other improvements:
On the first line, && should be ||. You also need to bail out if the fields are not filled.
SqlCredential is unnecessary, but you may want to put the connection string in a settings file.
SqlDataAdapter and DataTable are only necessary if you want to use data-binding to your UI. Otherwise you can use ExecuteReader and loop it whil (reader.Read())
In this case, you don't even need that, because you only check for existence of a row. So you can just use cmd.ExecuteScalar
You need to pass the connection object to the command, and you need to open the connection.
You need to dispose the connection and command with using.
Always pass the exact parameter type, using SqlDbType, along with the length, precision or scale if relevant.
Never store plain-text passwords. Salt-and-hash them, and compare the hashes on the server. Do not retrieve the stored hash to the client app.
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || textBox2.Text =="")
{
MessageBox.Show("Please fill up all fields");
return; //make sure to bail out
}
try
{
const string query = #"
select 1
from [login]
where username = #username
and password = #password;
";
using (var conn = new SqlConnection("Data Source=DESKTOP-90R7QPM;Initial Catalog=Librarypavilion;Integrated Security=True")
using (var cmd = new SqlCommand(query, conn)
{
cmd.Parameters.Add("#username", SqlDbType.NVarChar, 255).Value = textBox1.Text;
cmd.Parameters.Add("#password", SqlDbType.VarBinary, 128).Value = HashPassword(textBox1.Text, textBox2.Text);
conn.Open();
var exists = (cmd.ExecuteScalar() as int) == 1;
conn.Close();
if (exists)
{
MessageBox.Show(" User is Successfully login");
}
else
{
MessageBox.Show("unsuccessful");
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Consider using async and await to keep the UI alive.
private async void button1_Click(object sender, EventArgs e)
{
.....
await conn.OpenAsync();
var exists = ((await cmd.ExecuteScalarAsync()) as int) == 1;
conn.Close();
I have two tables in my database. Let's say table A and table B. table A values are put in checkedlistbox. The selected values in checkedlistbox then are put into table B. I tried to make a code however it wont work. Do you have any idea on how to make this problem work?
thanks ahead guys.
by the way im using c#.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Npgsql;
namespace WindowsFormsApplication1
{
public partial class Form8 : Form
{
public Form8()
{
InitializeComponent();
this.Load += Form8_Load;
button2.Click += button2_Click;
}
private void Form8_Load(object sender, EventArgs e)
{
string connstring = ("Server=localhost;Port=5432;User Id=postgres;Password=021393;Database=postgres;");
NpgsqlConnection conn = new NpgsqlConnection(connstring);
NpgsqlCommand cmd = new NpgsqlCommand("SELECT conname FROM condition", conn);
cmd.CommandType = CommandType.Text;
conn.Open();
using (NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
((ListBox)checkedListBox1).DataSource = dt;
((ListBox)checkedListBox1).DisplayMember = "conname";
((ListBox)checkedListBox1).DisplayMember = "conid";
string[] condition = dt.Rows[0]["conname"].ToString().Split(',');
}
}
private void button2_Click(object sender, EventArgs e)
{
string connstring = ("Server=localhost;Port=5432;User Id=postgres;Password=021393;Database=postgres;");
NpgsqlConnection conn = new NpgsqlConnection(connstring);
NpgsqlCommand cmd = new NpgsqlCommand("Insert into famhistory(famid) Values (#famid)", conn);
conn.Open();
cmd.Parameters.AddWithValue("#famid", checkedListBox1.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data has been saved");
conn.Close();
}
}
}
You have to iterate through all the selected items:
//check if any item is selected
if (checkedListBox1.SelectedItems.Count > 0)
{
//connect to database
string connstring = ("Server=localhost;Port=5432;User Id=postgres;Password=021393;Database=postgres;");
NpgsqlConnection conn = new NpgsqlConnection(connstring);
conn.Open();
//loop through all selected items
foreach (object item in checkedListBox1.CheckedItems)
{
//convert item to string
string checkedItem = item.ToString();
//insert item to database
NpgsqlCommand cmd = new NpgsqlCommand("Insert into famhistory(famid) Values (#famid)", conn);
cmd.Parameters.AddWithValue("#famid", checkedItem); //add item
cmd.ExecuteNonQuery();
}
//close connection
conn.Close();
MessageBox.Show("Data has been saved");
}
Note: I am executing all insert commands in one open connection, because opening and closing connection frequently is not best practice.
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
i am new to c#.net i found the following code in the web and i modified it but its not working
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace InsertUpdateDeleteDataGridView
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\bj\documents\visual studio 2013\Projects\InsertUpdateDeleteDataGridView\InsertUpdateDeleteDataGridView\Information.mdf;Integrated Security=True");
SqlCommand cmd;
SqlDataAdapter adapt;
//ID variable used in Updating and Deleting Record
int id = 0;
public Form1()
{
InitializeComponent();
//invok fn
DisplayData();
}
private void btninsert_Click(object sender, EventArgs e)
{
if(txtbxname.Text!="" && txtbxcountry.Text!="")
{
cmd = new SqlCommand("INSERT INTO users(name,country) VALUES(#name,#country)",con);
con.Open();
cmd.Parameters.AddWithValue("#name", txtbxname.Text);
cmd.Parameters.AddWithValue("#country", txtbxcountry.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("record added succesfully","Success");
DisplayData();
ClearData();
}
else
{
MessageBox.Show("please provide Details!","Error");
}
}
//displaying Data in DataGridView
private void DisplayData()
{
con.Open();
//creating obj of datatable method
DataTable dt= new DataTable();
dt = null;
adapt.Fill(dt);
dataGridView1.DataSource=dt;
con.Close();
}
//clearing datat
private void ClearData()
{
txtbxname.Text="";
txtbxcountry.Text="";
id=0;
}
private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
id=Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
txtbxname.Text=dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
txtbxcountry.Text=dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
}
//update record
private void btnupdate_Click(object sender, EventArgs e)
{
if(txtbxname.Text!="" && txtbxcountry.Text!="")
{
cmd=new SqlCommand("UPDATE users SET name=#name,state=#state WHERE id=#id ",con);
con.Open();
cmd.Parameters.AddWithValue("#id",id);
cmd.Parameters.AddWithValue("#name",txtbxname.Text);
cmd.Parameters.AddWithValue("#country",txtbxcountry.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("record updated succesfully","success");
con.Close();
DisplayData();
ClearData();
}
else
{
MessageBox.Show("please select the record to update!","erorrr!!");
}
}
//deleterecord
private void btndelete_Click(object sender, EventArgs e)
{
if(txtbxname.Text!="" && txtbxcountry.Text!="")
{
cmd=new SqlCommand("DELETE students WHERE id=#id",con);
con.Open();
cmd.Parameters.AddWithValue("#id",id);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("record deleted successfully!");
DisplayData();
ClearData();
}
else
{
MessageBox.Show("please select record to delete","error");
}
}
}
}
but when ever i try to run there is exception called in this line
adapt.filldata(dt);
private void DisplayData()
{
con.Open();
//creating obj of datatable method
DataTable dt= new DataTable();
dt=null;
adapt = new SqlDataAdapter("Select *from users ", con);
adapt.Fill(dt);
dataGridView1.DataSource=dt;
con.Close();
}
i again modified my creating object but the result is ame
i searched a lot but didnot got any answer so i am got stucked is there any one to help me
The adapt object has not been instantiated. You need to to create the object first.
this article gives a simple example of how to create the adapter and then call the fill method. you can not call methods on objects before creating them.
https://msdn.microsoft.com/en-us/library/bh8kx08z(v=vs.110).aspx
My problem is that I can't print out all the data from the table in my mysql database, I got out just last row in the given table "teacher". is there anyone who can help me find the error?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace ReadDataFromMysql
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string sql = " SELECT * FROM teacher ";
MySqlConnection con = new MySqlConnection("host=localhost;user=root;password=859694;database=projekt;");
MySqlCommand cmd = new MySqlCommand(sql, con);
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read()) {
data2txt.Text = reader.GetString("id");
datatxt.Text = reader.GetString("userId");
}
}
private void btnclose_Click(object sender, EventArgs e)
{
Close();
}
}
}
Your problem is that you are overwriting data2txt.Text and datatxt.Text on each row of data. if you want to see all of the data in those fields, something like this should do what you need:
data2txt.Text = string.Empty;
datatxt.Text = string.Empty;
while (reader.Read())
{
data2txt.Text += $"{reader.GetString("id")};";
datatxt.Text += $"{reader.GetString("userId")};";
}
You're assigning the value of each field instead of the value of the existing control's text plus the new value. Add a breakpoint to make sure you're getting multiple rows, but as your code is written, you would only see the result of one row in your form because you're overwriting on each iteration through the loop.
This code works.
private void getdata()
{
MySqlConnection connect = new MySqlConnection("SERVER=localhost; user id=root; password=; database=databasename");
MySqlCommand cmd = new MySqlCommand("SELECT ID, name FROM data WHERE ID='" + txtid.Text + "'");
cmd.CommandType = CommandType.Text;
cmd.Connection = connect;
connect.Open();
try
{
MySqlDataReader dr;
dr = cmd.ExecuteReader();
while(dr.Read())
{
txtID.Text = dr.GetString("ID");
txtname.Text = dr.GetString("name");
}
dr.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if(connect.State == ConnectionState.Open)
{
connect.Close();
}
}
Obviously your code shows the last row values of teacher table into your text fields on form.Because your are looping throught the datareader and assigning the values to textfiled.So each iteration it will overwright the previous values in textbox.
You should output the data before again writing in it:
data2txt.Text = reader.GetString("id");
datatxt.Text = reader.GetString("userId");
Or use a var to store all the data in with each 'read' and then output that var
varexample.Text += reader.GetString("id");