update bit datatype value in database - c#

try
{
UserMaster ObjUserMst = new UserMaster();
ObjUserMst.GetData("UPDATE MemberDetails SET Active = 0 WHERE Member_No = '" + txtmemberno.Text + "'");
MessageBox.Show("Installment Close Successfully.", "Close Installment", MessageBoxButtons.OK, MessageBoxIcon.Information);
btndebit.Visible = true;
btndebit.Visible = false;
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message.ToString(), "btncloseinstallment_Click", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
its get data code
public DataTable GetData(string Query)
{
string cn = GlobalClass.ConnectionStringGet();
Con = new SqlConnection(cn);
cmd = new SqlCommand();
cmd.Connection = Con;
if (cmd.Connection.State == ConnectionState.Closed)
{
cmd.Connection.Open();
}
SqlTransaction ObjTrans = cmd.Connection.BeginTransaction();
cmd.Transaction = ObjTrans;
cmd.CommandType = CommandType.Text;
cmd.CommandText = Query;
cmd.CommandTimeout = 500;
SqlDataReader dreader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dreader);
Con.Close();
Con.Dispose();
return dt;
}
i have winforms.
i have memberdetails Table - in this Active Field & its datatype is BIT. its
default value is 1. but i need to update it to 0.
1 = ture
0 = false
when i tried above code Active Field data didnt update
but i got message "Installment Close Successfully."
http://i.stack.imgur.com/mkuhW.png
http://i.stack.imgur.com/ToXFV.png
I upload my images on above link
help me guys.. sorry if i didnt explain very well bcz i m new here

ok i got it.
string constring = GlobalClass.ConnectionStringGet();
string sqlUpdate = "UPDATE MemberDetails SET Active = '0' WHERE Member_No = '" + txtmemberno.Text + "'";
SqlConnection conDatabase = new SqlConnection(constring);
SqlCommand cmdd = new SqlCommand(sqlUpdate, conDatabase);
conDatabase.Open();
cmdd.ExecuteNonQuery();
conDatabase.Close();
MessageBox.Show("Installment Close Successfully.");
its update Active Field 1 to 0 successfully.

Related

How can i solve this problem kindly "Fatal error encountered during command execution."

I´m having some issue inserting a new record to this table.
Though can't seem to find the real issue within my code.
try
{
conn = new MySqlConnection(cs.ConnString);
conn.Open();
cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = "insert into Depense_Vehicule (Code,Date,Responsable,Source_Cr,Numero_Plaque_Dt,Possession,Chauffeur,Categorie,Type,Libelle,Montant_$,Montant_FC,Taux_Echange,Total_$,Status)" +
"VALUES (#d1,#d2,#d3,#d4,#d5,#d6,#d7,#d8,#d9,#d10,#d11,#d12,#13,#14,#15)";
cmd.Parameters.AddWithValue("d1", Code_ADV_txt.Text);
cmd.Parameters.AddWithValue("d2", Date_ADVe_dt.Text);
cmd.Parameters.AddWithValue("d3", Responsable_ADV_txt.Text);
cmd.Parameters.AddWithValue("d4", Source_ADV_cb.Text);
cmd.Parameters.AddWithValue("d5", Numero_Plaque_ADV_txt.Text);
cmd.Parameters.AddWithValue("d6", Possesion_ADV_txt.Text);
cmd.Parameters.AddWithValue("d7", Chauffeur_ADV_cb.Text);
cmd.Parameters.AddWithValue("d8", Categorie_ADV_cb.Text);
cmd.Parameters.AddWithValue("d9", Type_Payment_ADV_cb.Text);
cmd.Parameters.AddWithValue("d10", Libelle_ADV_txt.Text);
cmd.Parameters.AddWithValue("d11", MontantDollars_ADV_txt.Text);
cmd.Parameters.AddWithValue("d12", MontantFranc_ADV_txt.Text);
cmd.Parameters.AddWithValue("d13", TauxEchange_ADV_txt.Text);
cmd.Parameters.AddWithValue("d14", TotalDollars_ADV_txt.Text);
cmd.Parameters.AddWithValue("d15", Status_ADV_cb.Text);
MySqlDataReader myReader;
myReader = cmd.ExecuteReader();
conn.Close();
MessageBox.Show("Record Ajouter");
Source_ADV_cb.SelectedIndex = -1;
Chauffeur_ADV_cb.SelectedIndex = -1;
Numero_Plaque_ADV_txt.Text = "";
Possesion_ADV_txt.Text = "";
Categorie_ADV_cb.SelectedIndex = -1;
Type_Payment_ADV_cb.SelectedIndex = -1;
MontantDollars_ADV_txt.Text = "";
MontantFranc_ADV_txt.Text = "";
TotalDollars_ADV_txt.Text = "";
Status_ADV_cb.SelectedIndex = -1;
Libelle_ADV_txt.Text = "";
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace);
}
finally
{
conn.Close();
}
I think you must use cmd.ExecuteNonQuery instead of cmd.ExecuteReader().
ExecuteReader is for run SQL SELECT command.
I hope this answer is useful for you.

How to get an integer value from SQL database to a variable in windows forms (C#)?

I've created a form called BookSeat which takes no.of seats as an input and calculate the total fare.
Here's my code:
{
try
{
DB db = new DB();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT [fare] FROM [dbo].[Train] WHERE name = '" + textBoxName.Text + "' ";
cmd.Connection = db.GetConnection();
db.openConnection();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
int d = dr.GetInt32(0);
int noOfSeats = comboBoxNoOfSeats.SelectedIndex;
int totalfare;
totalfare = noOfSeats * d;
textBoxTotalFare.Text = totalfare.ToString();
db.closeConnection();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This shows and error : Invalid attempt to read when no data is present
SqlDataReader has the method called Read which reads all the data inside sqldatareader. But you have to call this function inside while loop.
try
{
DB db = new DB();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT [fare] FROM [dbo].[Train] WHERE name = '" + textBoxName.Text + "' ";
cmd.Connection = db.GetConnection();
db.openConnection();
SqlDataReader dr = cmd.ExecuteReader();
While(dr.Read())
{
//Get value by using column name;
int d = Convert.ToInt32(dr["columnname"]);
int noOfSeats = comboBoxNoOfSeats.SelectedIndex;
int totalfare;
totalfare = noOfSeats * d;
textBoxTotalFare.Text = totalfare.ToString();
}
dr.Close();
db.closeConnection();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}

How to delete multiple rows in C# using a SQL query?

I have code for deleting a row in C# using a SqlCommand. But I want to delete multiple rows. Can anyone help me with this? I am new to C#.
This is my code - please help. Thank you in advance.
foreach (DataGridViewRow dr in dataGrid1.SelectedRows)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=DDBULK10\SQLEXPRESS;Initial Catalog=MasterList; Integrated Security = True";
if (dr.Index > 0)
{
int selectedIndex = dataGrid1.SelectedRows[0].Index;
int rowID = int.Parse(dataGrid1[0, selectedIndex].Value.ToString());
string sql = "DELETE FROM ActiveUser WHERE EmpId = #EmpId";
SqlCommand deleteRecord = new SqlCommand();
deleteRecord.Connection = con;
deleteRecord.CommandType = CommandType.Text;
deleteRecord.CommandText = sql;
SqlParameter RowParameter = new SqlParameter();
RowParameter.ParameterName = "#EmpId";
RowParameter.SqlDbType = SqlDbType.Int;
RowParameter.IsNullable = false;
RowParameter.Value = rowID;
deleteRecord.Parameters.Add(RowParameter);
deleteRecord.Connection.Open();
deleteRecord.ExecuteNonQuery();
//deleteRecord.Connection.Close();
MessageBox.Show("Record Successfully Deleted");
SqlDataAdapter sda = new SqlDataAdapter("select * from ActiveUser", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGrid1.DataSource = dt;
}
else if (dialogResult == DialogResult.No)
{
this.Refresh();
}
}
You can build a comma separated userid list like -
string strUserIds = string.Empty();
for(int i=0; i<dataGrid.Count;i++)
{
strUserIds = strUserIds +","+ dataGrid.SelectedRows[0].Cells[0].Value;
}
--Remove last unwanted comma from strUserIds
then execute sql query as "DELETE FROM EmployeeTbl WHERE UserID in (" + strUserIds + ")"
This will delete multiple records from table.
Just Make some changes in Your Coding !
Delete All Selected Rows
Run Your select * from ActiveUser
public void deldata()
{
foreach (DataGridViewRow dr in dataGrid1.SelectedRows)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=DDBULK10\SQLEXPRESS;Initial Catalog=MasterList; Integrated Security = True";
if (dr.Index > 0)
{
int selectedIndex = dataGrid1.SelectedRows[0].Index;
int rowID = int.Parse(dataGrid1[0, selectedIndex].Value.ToString());
string sql = "DELETE FROM ActiveUser WHERE EmpId = #EmpId";
SqlCommand deleteRecord = new SqlCommand();
deleteRecord.Connection = con;
deleteRecord.CommandType = CommandType.Text;
deleteRecord.CommandText = sql;
SqlParameter RowParameter = new SqlParameter();
RowParameter.ParameterName = "#EmpId";
RowParameter.SqlDbType = SqlDbType.Int;
RowParameter.IsNullable = false;
RowParameter.Value = rowID;
deleteRecord.Parameters.Add(RowParameter);
deleteRecord.Connection.Open();
deleteRecord.ExecuteNonQuery();
//deleteRecord.Connection.Close();
MessageBox.Show("Record Successfully Deleted");
}
else if (dialogResult == DialogResult.No)
{
this.Refresh();
}
}
}
public void showdata()
{
SqlDataAdapter sda = new SqlDataAdapter("select * from ActiveUser", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGrid1.DataSource = dt;
}
You can use something like this; i didn't test the code but it should work if you create the parameters you need, before running code you have to create a type table, please see the link for details.
using (connection)
{
string sql ="Delete from YourTable t join #yourTypeTable i on t.id = i.Id:";
SqlCommand deleteCommand = new SqlCommand(sql, connection);
SqlParameter tvpParam = deleteCommand.Parameters.AddWithValue("#yourTypeTable", yourIdList);
tvpParam.SqlDbType = SqlDbType.Structured;
tvpParam.TypeName = "dbo.yourTypeTable";
deleteCommand.ExecuteNonQuery();
}

why Integer value is not inserted in access database

Iam trying to insert integer value into access database but its giving me Object cannot be cast from DBNull to other types. error but in datagridview im putting a value but still show me this error
string Medicine_Name = dataGridView1.Rows[e.RowIndex].Cells["Medicine_Name"].Value.ToString();
string Dealer_name = dataGridView1.Rows[e.RowIndex].Cells["Dealer_name"].Value.ToString();
int Availability =Convert.ToInt16(dataGridView1.Rows[e.RowIndex].Cells["Availability"].Value);
if (dataGridView1.IsCurrentRowDirty)
{
string connectionString = null;
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string cmd1 = "insert into Medicine_Available_Detail(Medicine_Name,Dealer_name,Availability) values(#Medicine_Name,#Dealer_name,#Availability)";
OleDbCommand cmd = new OleDbCommand(cmd1, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Medicine_Name",Medicine_Name);
cmd.Parameters.AddWithValue("#Dealer_name", Dealer_name);
cmd.Parameters.AddWithValue("#Availability", Availability);
con.Open();
int n = cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("Data Inserted Successfully", "Data Inserted ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
The "pencil" indicates that the row is being edited, thus - even with an entered value of 2 - the value of Availability can very well be null.
So your concept seems faulty; you should not attempt to insert data when dataGridView1.IsCurrentRowDirty is true but when it is false.
Finally got a solution on this i change my code dataGridView1_RowLeave to dataGridView1_CellValueChanged and its working fine
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
med_id = dataGridView1.Rows[e.RowIndex].Cells["Med_id"].Value.ToString();
if (med_id == "")
{
med_id1 = 0;
}
else
{
med_id1 = Convert.ToInt32( dataGridView1.Rows[e.RowIndex].Cells["Med_id"].Value.ToString());
}
if (med_id1 == 0)
{
try
{
string Medicine_Name = dataGridView1.Rows[e.RowIndex].Cells["Medicine_Name"].Value.ToString();
string Dealer_name = dataGridView1.Rows[e.RowIndex].Cells["Dealer_name"].Value.ToString();
int Availability = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["Availability"].Value.ToString());
string cmd1 = "insert into Medicine_Available_Detail(Medicine_Name,Dealer_name,Availability) values(#Medicine_Name,#Dealer_name,#Availability)";
OleDbCommand cmd = new OleDbCommand(cmd1, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Medicine_Name", Medicine_Name);
cmd.Parameters.AddWithValue("#Dealer_name", Dealer_name);
cmd.Parameters.AddWithValue("#Availability", Availability);
con.Open();
int n = cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("Data Inserted Successfully", "Data Inserted ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Load_data();
dataGridView1.Refresh();
}
catch (Exception ex)
{
}
}
else
{
string Medicine_Name = dataGridView1.Rows[e.RowIndex].Cells["Medicine_Name"].Value.ToString();
string Dealer_name = dataGridView1.Rows[e.RowIndex].Cells["Dealer_name"].Value.ToString();
int Availability = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["Availability"].Value.ToString());
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd = con.CreateCommand();
cmd.CommandText = "update Medicine_Available_Detail set Medicine_Name='" + dataGridView1.Rows[e.RowIndex].Cells["Medicine_Name"].Value.ToString() + "',Dealer_name='" + dataGridView1.Rows[e.RowIndex].Cells["Dealer_name"].Value.ToString() + "',Availability='" + Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["Availability"].Value.ToString())+ "'where Med_id=" + med_id1 + "";
con.Open();
int n = cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("Data Updated Successfully", "Data Inserted ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Load_data();
dataGridView1.Refresh();
}
}

Combobox Showing Old Database Values

I retrived values by the use of SqlCommand and SqlReader from column and stored in List<String> and the added to ComboBox(Type:DropDownList) but Eventhough i have deleted Some of this values from database Combobox is still showing it.
I am clearing items befor allocating by
mycombobox.Items.Clear();
It looks as it is not affected by values I retrive every time when the Form gets Loaded.
SqlDataReader rdr1 = null;
SqlConnection con1 = null;
SqlCommand cmd1 = null;
try
{
List<string> namesCollection=new List<string>();
// Open connection to the database
string ConnectionString = #"Data Source=MyPC-PC\SQLEXPRESS;Initial Catalog=DryDB;Integrated Security=True";
con1 = new SqlConnection(ConnectionString);
con1.Open();
cmd1 = new SqlCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "SELECT PName from MASTER order by PName";
cmd1.Connection = con1;
rdr1 = cmd1.ExecuteReader();
namesCollection.Add("Select");
if (rdr1.Read()==true)
{
do
{
namesCollection.Add("" + rdr1[0].ToString());
} while (rdr1.Read()) ;
}
else
{
}
foreach(string pname in namesCollection)
cb.Items.Add(pname);
namesCollection.Clear();
cb.SelectedIndex =0;
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
if (rdr1 != null)
rdr1.Close();
if (con1.State == ConnectionState.Open)
con1.Close();
}
Thanks in advance.
Use the DataSource property of the Combobox instead of the adding the items one by one. So your code will be something like the following:
SqlDataReader rdr1 = null;
SqlConnection con1 = null;
SqlCommand cmd1 = null;
try
{
List<string> namesCollection = new List<string>();
// Open connection to the database
string ConnectionString = #"Data Source=MyPC-PC\SQLEXPRESS;Initial Catalog=DryDB;Integrated Security=True";
con1 = new SqlConnection(ConnectionString);
con1.Open();
cmd1 = new SqlCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "SELECT PName from MASTER order by PName";
cmd1.Connection = con1;
rdr1 = cmd1.ExecuteReader();
namesCollection.Add("Select");
if (rdr1.Read()==true)
{
do
{
namesCollection.Add("" + rdr1[0].ToString());
} while (rdr1.Read()) ;
}
else
{
}
//Replace this part...
//foreach(string pname in namesCollection)
//cb.Items.Add(pname);
//With this...
cb.DataSource = namesCollection;
cb.SelectedIndex =0;
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
if (rdr1 != null)
rdr1.Close();
if (con1.State == ConnectionState.Open)
con1.Close();
}
There is a similar question here
Hope this helps
Let's say the code to populate the ComboBox is placed in the populate_cb() method
private void populate_cb(){
cb.Items.Clear();
SqlDataReader rdr1 = null;
SqlConnection con1 = null;
SqlCommand cmd1 = null;
try
{
// Open connection to the database
string ConnectionString = #"Data Source=MyPC-PC\SQLEXPRESS;Initial Catalog=DryDB;Integrated Security=True";
con1 = new SqlConnection(ConnectionString);
con1.Open();
cmd1 = new SqlCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "SELECT PName from MASTER order by PName";
cmd1.Connection = con1;
rdr1 = cmd1.ExecuteReader();
cb.Items.Add("Select");
while(rdr1.Read())
{
cb.Items.Add(rdr1[0].ToString());
}
cb.SelectedIndex =0;
con1.Close();
}
catch(Exception ex){
// handle exception
}
}//end of populate_cb()
Call populate_cb() method form form_load() and
Call from the place after the deletion process
You need to make sure your deletion process really deletes the records from database!

Categories