How can I Delete Data in a Database Using ComboBox in C#? - c#

Here is a Picture of My Table Named CategoryTable
I used The Following Code to Delete Data from the Above Table using a ComboBox which is named as SelectCategoryComboBoxBut it does nothing.it acts like an un-programed button.
here is my code:
try
{
String conString = ConfigurationManager.ConnectionStrings["mfcdb"].ConnectionString;
String query = "DELETE FROM CategoryTable WHERE CategoryName='" + SelectCategoryComboBox.SelectedText + "'";
using (SqlConnection con = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
}
}
catch{
MessageBox.Show("Error");
}

Change
SelectCategoryComboBox.SelectedText
to
SelectCategoryComboBox.SelectedItem.ToString()

Related

Checking if username is available in database

I'm trying to check if the username is already in use in C# database and it's giving me this error
SqlConnection cn = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\admin\Desktop\241 Project sem 1 2020-2021\Online Banking - ITIS 241 project group 9\UobBankDatabase.mdf; Integrated Security = True; Connect Timeout = 30");
cn.Open();
SqlCommand cmd = new SqlCommand("select * from LoginTable where user_name='" + textBox1.Text + "'", cn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
dr.Close();
MessageBox.Show("Username Already exist please try another ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
dr.Close();
}
and yes I'm a newbie
Use this:
SqlCommand cmd = new SqlCommand("Select count(*) from LoginTable where user_name='" + textBox1.Text + "'", cn);
Then:
var dr = cmd.ExecuteScalar();
if (dr != null)
{
//Exists
}
else
{
//Unique username
}
Google it please:
Since the error is SqlException: Invalid object name 'Movie' , that
means the table named 'Movie' has not created or the Database you are
referring has not created. To see if the Database or table 'Movie' has
created, open SQL Server Object Explorer and check the Database name
is the same as in appsettings. json
And Please tell us at what line do you get that?
Is that this line =>if (dr.Read())
Let's extract method for the check:
private static bool NameAvailable(string name) {
//DONE: wrap IDisposable into using
using (SqlConnection cn = new SqlConnection("Connection String Here")) {
cn.Open();
//DONE: keep Sql readable
//DONE: make Sql parametrize
//DONE: select 1 - we don't want entire record but a fact that record exists
string sql =
#"select 1
form LoginTable
where user_name = #prm_user_name";
using (var cmd = new SqlCommand(sql, cn)) {
cmd.Parameters.Add("#prm_user_name", SqlDbType.VarChar).Value = name;
using (var dr = cmd.ExecuteReader()) {
return !dr.Read(); // Not available if we can read at least one record
}
}
}
}
Then you can put
if (!NameAvailable(textBox1)) {
// Let's be nice and put keyboard focus on the wrong input
if (textBox1.CanFocus)
textBox1.Focus();
MessageBox.Show("Username Already exist please try another ",
"Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
some changes only.it is better to get what is the error than a temporary solution so print your query first and run it in the sqlserver . also add initial catalog instead of attacjing mdf files its way better in my opinion.
<connectionStrings>
<add name="stringname" connectionString="Data Source=mssql;Initial Catalog=databasename; Persist Security Info=True;User ID=sa;Password=*****;MultipleActiveResultSets=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
using a connection string instead also
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["stringname"].ConnectionString);
cn.Open();
string query = "select * from LoginTable where user_name='" + textBox1.Text.ToString() + "'";
SqlCommand cmd = new SqlCommand(query, cn);
SqlDataReader dr = cmd.ExecuteReader();
//print query if error and comment the execute reader section when printing the query to know the error Respone.Write(query);
if (!dr.HasRows)
{
// ur code to insert InsertItemPosition values
}
else
{
//show username exist
}
dr.Close();
Try this:
string conString = ConfigurationManager.ConnectionStrings["YourConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("SELECT COUNT(UserName) as UserCount FROM LoginTable WHERE user_name = #user_name", con))
{
con.Open();
cmd.Parameters.AddWithValue("#user_name", TextBox1.Text);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows)
{
if(Convert.ToInt32(dr["UserCount"].ToString()) >= 1)
{
// Exists
}
else
{
// Doesn't Exist
}
}
}
con.Close();
}
}

Don't show insert tile second insert do in localDataBace

I want insert some data to localdatabace and insert is successfully done but don't show in my datagridview tile second insert do for debog it I Call Select All end of my insert and see the last insert don't show in it but whene i insert a next data , last data will be showing can every one help me pleas?
public void connect()
{
String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\hana\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection sql = new SqlConnection(conString);
String sqll = "Insert into TblBank (txtTodayDate" +
",txtSahebanHesab" +
",txtShobe" +
",txtShomareMoshtari" +
",txtShoareHesab" +
",cmbNoeHesab" +
",txtSarresid" +
")";
try
{
sql.Open();
SqlDataAdapter sda = new SqlDataAdapter(sqll, sql);
SqlCommand sc = new SqlCommand(sqll,sql);
sc.Parameters.AddWithValue("todayDate", new PersianDateTime(dtpTodayDate.the_date).ToString("yyyy/MM/dd"));
sc.Parameters.AddWithValue("sahebanHesab", txtSahebHesabName.Text);
sc.Parameters.AddWithValue("shobe", txtshobe.Text);
sc.Parameters.AddWithValue("shomareMoshtari", txtShomareMoshtari.Text);
sc.Parameters.AddWithValue("shoareHesab", txtShomareHesab.Text);
sc.Parameters.AddWithValue("noeHesab", cmbNoeHesab.SelectedIndex);
sc.Parameters.AddWithValue("sarresid", txtSarResidMah.Text);
sc.ExecuteNonQuery();
sql.Close();
select();
}
catch (Exception ex)
{
}
}
and select is
private void select()
{
String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\hana\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection cn = new SqlConnection(conString);
String sqlString = "SELECT * FROM TblBank Order BY Id desc ";
SqlConnection sql = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand(sqlString, cn);
try {
sql.Open();
SqlDataAdapter sa = new SqlDataAdapter(sqlString, sql);
using (SqlDataReader read = sa.SelectCommand.ExecuteReader())
{
if (read.Read())
{
DataTable dt = new DataTable();
dt.Load(read);
this.tblBankDataGridViewX.DataSource = dt;
}
}
sql.Close();
}
catch (Exception ex)
{
}
}
The DataReader.Read() method will iterate result set before DataTable.Load(). Because the DataReader is a forward-only stream, it has empty result set when DataTable.Load() executes and DataTable content is still empty while setting DataSource for DataGridView. Try DataReader.HasRows property to check result set availability:
using (SqlConnection cn = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(sqlString, cn))
{
try
{
cn.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
// check if the reader returns result set
if (read.HasRows)
{
DataTable dt = new DataTable();
dt.Load(read);
this.tblBankDataGridViewX.DataSource = dt;
}
}
}
catch (Exception ex)
{
// do something
}
}
}

Why doesn't my C# code update the SQL Server database although I get the correct number of affected rows

I created the following code:
public static bool setHeadword(int id, string headword)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\pms.mdf;Integrated Security=True";
conn.Open();
SqlCommand command = new SqlCommand("UPDATE headwords SET Headword = #headword WHERE Id = #id", conn);
command.Parameters.AddWithValue("#headword", headword);
command.Parameters.AddWithValue("#id", id);
int result = command.ExecuteNonQuery();
conn.Close();
return true;
}
But the code doesn't work because the value in the database doesn't change.
If I run the code manually in the database the change takes place. But it won't work with C#.
Also the result variable are holding the right number of affected rows (1 in this case).
I'm not sure I have to flush the changes or something else.
Thanks for your help and best regards
Franz
static void Update(int id, string headword)
{
try
{
//You should create connectionString with correct details otherwise fail connection
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=123";
using (SqlConnection conn =
new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("UPDATE headwords SET Headword=#headword" +
" WHERE Id=#Id", conn))
{
cmd.Parameters.AddWithValue("#Id", id);
cmd.Parameters.AddWithValue("#headword", headword);
int rows = cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
//Handle sql Exception
}
}

inserting every row in grideview

I am trying to insert every row in the GridView into a table on a click of button. My problem with the code below is that the data was inserted but i cant handle the exception i used this code
string constring = #"Data Source=WINCTRL-RDJN6O6;Initial Catalog=Care_AlexDemo;Integrated Security=True";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO TeseI VALUES(#Emp_name, #Emp_number)", con))
{
cmd.Parameters.AddWithValue("#Emp_name", row.Cells["Emp_name"].Value);
cmd.Parameters.AddWithValue("#Emp_number", row.Cells["Emp_number"].Value);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
MessageBox.Show("Records inserted.");
I don't understand what is the variable 'row', I suppose it means every row in the DataGridView.Rows, so you try to insert rows to the database one by one? Generally I'd like to insert all rows once with 'INSERT INTO [TABLE_NAME] SELECT ...' statement. so the code may be like this:
StringBuilder strsql = new StringBuilder("INSERT INTO TeseI ");
foreach (var row in DataGridView.Rows)
{
strsql.AppendFormat(" SELECT '{0}', '{1}' UNION ALL ", row.Cells["Emp_name"].Value, row.Cells["Emp_number"].Value);
}
// remove the last 'UNION ALL '
strsql.Remove(strsql.Length - 10, 10);
string constring = #"Data Source=WINCTRL-RDJN6O6;Initial Catalog=Care_AlexDemo;Integrated Security=True";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand(strsql.ToString(), con))
{
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
MessageBox.Show("Records inserted.");
by the way, I think we can remove the explicit invoke of 'con.Open()' and 'con.Close()' methods, since we use the 'using' statement
I just give the way I do cause you didn't show the exception message. Anyway,
Hope this can help

If record exists dont insert

I'm trying something out but cant figure it out. So what i'm trying is that if the user inputs something inside txtISN and it already exists inside of the database, the record wont be inserted. I also want a error msg to pop up when a record wasnt inserted and when a record is inserted I want an message to pop up saying that the record was inserted succesfully.
Thanks for the help y'all!
string _connStr = #"Data Source = EJQ7FRN; Initial Catalog = BES; Integrated Security = True";
string _query = "INSERT INTO [BES_S] (ISN,Titel,Name) values (#ISN,#Titel,#Name)";
using (SqlConnection conn = new SqlConnection(_connStr))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = _query;
comm.Parameters.AddWithValue("#ISN", txtISN.Text);
comm.Parameters.AddWithValue("#Titel",txtTitel.Text);
comm.Parameters.AddWithValue("#Name", txtName.Text);
try
{
conn.Open();
comm.ExecuteNonQuery();
}
catch (SqlException ex)
{
}
}
}
You need to change your query a bit, but you can use MySql's DUAL keyword to do this:
string _connStr = #"Data Source = EJQ7FRN; Initial Catalog = BES; Integrated Security = True";
string _query = "INSERT INTO [BES_S] (ISN,Titel,Name) ";
_query = _query + " SELECT #ISN, #Titel, #Name FROM DUAL";
_query = _query + " WHERE NOT EXISTS (SELECT ISN WHERE ISN=#ISN)";
using (SqlConnection conn = new SqlConnection(_connStr))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = _query;
comm.Parameters.AddWithValue("#ISN", txtISN.Text);
comm.Parameters.AddWithValue("#Titel",txtTitel.Text);
comm.Parameters.AddWithValue("#Name", txtName.Text);
try
{
conn.Open();
comm.ExecuteNonQuery();
}
catch (SqlException ex)
{
}
}
}
DUAL is like a dummy table that you can use to SELECT from.
Let the database take care of this using a unique constraint/index:
alter table bes_s add constraint unq_bes_ISN unique (ISN);
This will cause the database to generate an error if a duplicate ISN is inserted. You can put one or more columns for the unique constraint (in case this single column is not the exact definition of uniqueness).

Categories