System.Data.SqlClient.SqlException: 'Invalid column name 'Project_ID_Backend'.' - c#

I have written this C# application that acts as a database to keep track of projects and notes on the projects. I had it all working fine but then I needed to change the ProjectID column to not be an integer value (the project id's start with letters) so I had to add a new column to be able to accept this.
I kept the old project ID and renamed it "Project_ID_Backend" so my code would still work. (The way I have it written was that if the Project ID was greater than 0, things would happen.
Now whenever I click on the datagridview I am getting an error message. It used to work where when you would click on the datagridview, the contents of that row in the grid would populate the textboxes automatically making it easy to make changes to the records.
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Generic;
namespace SFTool
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection("my connection string here");
public int ProjectIDBackend;
public int NoteID;
private void MainForm_Load(object sender, System.EventArgs e)
{
// load in sql data to the data grid view
GetProjectsDataset();
// load notes database into the notesDataGridView
GetNotesDataset();
PopulateListBoxes();
}
private void PopulateListBoxes()
{
List<string> ProjectStatusList = new List<string>();
ProjectStatusList.Add("Working");
ProjectStatusList.Add("Submitted");
ProjectStatusList.Add("Reviewed");
ProjectStatusList.Add("Completed");
projectStatusListBox.DataSource = ProjectStatusList;
List<string> ProjectTypeList = new List<string>();
ProjectTypeList.Add("New build");
ProjectTypeList.Add("MAC");
ProjectTypeList.Add("Decom");
projectTypeListBox.DataSource = ProjectTypeList;
}
private void GetNotesDataset()
{
SqlCommand cmd = new SqlCommand("SELECT * FROM sfNotes", con);
DataTable dtNotes = new DataTable();
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
dtNotes.Load(sdr);
con.Close();
notesDataGridView.DataSource = dtNotes;
// Automatically resizes the columns to fit the data grid view
notesDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
notesDataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
}
private void GetProjectsDataset()
{
SqlCommand cmd = new SqlCommand("SELECT Project_ID AS 'Project ID', First_Name AS 'First Name', Last_Name AS 'Last Name', Project_Type AS 'Type', Project_Status AS 'Project Status', Last_Updated AS 'Last Updated', Last_Updated_By AS 'Last Updated By', Project_ID_Backend AS 'P.ID Backend' " +
"FROM sfProjects", con);
DataTable dt = new DataTable();
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
dt.Load(sdr);
con.Close();
dataGridView.DataSource = dt;
// Automatically resizes the columns to fit the data grid view
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
}
private void insertButton_Click(object sender, EventArgs e)
{
// allow user to insert data into the database, or create new records
if (IsValid())
{
SqlCommand cmd = new SqlCommand("INSERT INTO sfProjects VALUES (#Project_ID, #FirstName, #LastName, #Project_Type, #Project_Status, #Last_Updated, #Last_Updated_By)", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Project_ID", projectIDTextBox.Text);
cmd.Parameters.AddWithValue("#FirstName", firstNameTextBox.Text); // maps #FirstName to the firstName textbox
cmd.Parameters.AddWithValue("#LastName", lastNameTextBox.Text);
cmd.Parameters.AddWithValue("#Project_Type", projectTypeListBox.SelectedItem);
cmd.Parameters.AddWithValue("#Last_Updated", DateTime.Now);
cmd.Parameters.AddWithValue("#Last_Updated_By", System.Environment.MachineName);
cmd.Parameters.AddWithValue("#Project_Status", projectStatusListBox.SelectedItem);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("New record has been successfully added to the database", "Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
// now update/REFRESH the database so it shows the new record
GetProjectsDataset();
// reset form controls
ResetFormControls();
}
}
// data validation. (Make sure name is never empty)
private bool IsValid()
{
if (firstNameTextBox.Text == string.Empty)
{
MessageBox.Show("First Name is required.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
// else return true (it is valid)
return true;
}
private bool IsNotesValid()
{
if (notesProjectIDTextBox.Text == string.Empty)
{
MessageBox.Show("Project ID is required in order to assign a note to a project.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
// else return true (it is valid/Project ID was provided)
return true;
}
private void resetButton_Click(object sender, EventArgs e)
{
// resets, or clears, the textboxes
ResetFormControls();
GetProjectsDataset();
GetNotesDataset();
}
private void ResetFormControls()
{
ProjectIDBackend = 0; // resets value of projectID after clicking reset
projectIDTextBox.Clear();
firstNameTextBox.Clear();
lastNameTextBox.Clear();
projectTypeListBox.ClearSelected();
projectStatusListBox.ClearSelected();
notesProjectIDTextBox.Clear();
notesTextBox.Clear();
searchProjectsTextBox.Clear();
projectIDTextBox.Focus();
}
private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
// WHen you click on a row in the data grid, the textboxes will automatically populate with that rows values
ProjectIDBackend = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[7].Value);
projectIDTextBox.Text = dataGridView.SelectedRows[0].Cells[0].Value.ToString();
firstNameTextBox.Text = dataGridView.SelectedRows[0].Cells[1].Value.ToString();
lastNameTextBox.Text = dataGridView.SelectedRows[0].Cells[2].Value.ToString();
projectTypeListBox.SelectedItem = dataGridView.SelectedRows[0].Cells[3].Value.ToString();
projectStatusListBox.SelectedItem = dataGridView.SelectedRows[0].Cells[4].Value.ToString();
// Filter the notes grid to only show notes for the row the user clicks
SqlCommand cmd = new SqlCommand("SELECT * FROM sfNotes WHERE Project_ID_Backend= #Project_ID_Backend", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Project_ID_Backend", this.ProjectIDBackend);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
DataTable dtF = new DataTable();
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
dtF.Load(sdr);
con.Close();
notesDataGridView.DataSource = dtF;
// Automatically resizes the columns to fit the data grid view
notesDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
notesDataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
}
private void updateButton_Click(object sender, EventArgs e)
{
if (ProjectIDBackend > 0)
{
SqlCommand cmd = new SqlCommand("UPDATE sfProjects SET Project_ID= #Project_ID, First_Name= #First_Name, Last_Name= #Last_Name, Project_Type= #Project_Type, Project_Status= #Project_Status, Last_Updated= #Last_Updated, Last_Updated_By= #Last_Updated_By WHERE Project_ID= #Project_ID", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Project_ID", projectIDTextBox.Text);
cmd.Parameters.AddWithValue("#First_Name", firstNameTextBox.Text);
cmd.Parameters.AddWithValue("#Last_Name", lastNameTextBox.Text);
cmd.Parameters.AddWithValue("#Project_Type", projectTypeListBox.SelectedItem);
cmd.Parameters.AddWithValue("#Project_Status", projectStatusListBox.SelectedItem);
cmd.Parameters.AddWithValue("#Last_Updated", DateTime.Now);
cmd.Parameters.AddWithValue("#Last_Updated_By", System.Environment.MachineName);
cmd.Parameters.AddWithValue("#Project_ID_Backend", this.ProjectIDBackend);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record is successfully updated", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information);
// now update/REFRESH the database so it shows the new record
GetProjectsDataset();
// reset form controls
ResetFormControls();
}
else
{
MessageBox.Show("Please select a record to update", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void deleteButton_Click(object sender, EventArgs e)
{
// Confirm user wants to delete by asking "Are you sure?"
var confirmDelete = MessageBox.Show("Are you sure you want to delete this record? This action cannot be undone.",
"Confirm Delete",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning);
if (confirmDelete == DialogResult.Yes)
{
if (ProjectIDBackend > 0)
{
SqlCommand cmd = new SqlCommand("DELETE FROM sfProjects WHERE Project_ID_Backend= #Project_ID_Backend", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Project_ID_Backend", this.ProjectIDBackend); // Project_ID equals "this" ProjectID that I clicked on
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record is successfully deleted from the system", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information);
// now update/REFRESH the database so it shows the new record
GetProjectsDataset();
// reset form controls
ResetFormControls();
}
else
{
MessageBox.Show("Please select a record to delete", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
}
}
private void notesButton_Click(object sender, EventArgs e)
{
// Addes note into the database
if (IsNotesValid())
{
SqlCommand cmd = new SqlCommand("INSERT INTO sfNotes VALUES (#Project_ID, #Notes, #Note_Created, #Note_Created_By)", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Project_ID", notesProjectIDTextBox.Text); // maps #Project_ID to the notesProjectID textbox
cmd.Parameters.AddWithValue("#Notes", notesTextBox.Text);
cmd.Parameters.AddWithValue("#Note_Created", DateTime.Now);
cmd.Parameters.AddWithValue("#Note_Created_By", System.Environment.MachineName);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("New note has been successfully added to the database for Project ID " + this.ProjectIDBackend, "Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
// now update/REFRESH the database so it shows the new record
GetProjectsDataset();
GetNotesDataset();
// reset form controls
ResetFormControls();
}
}
private void notesDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
// WHen you click on a row in the data grid, the textboxes will automatically populate with that rows values
NoteID = Convert.ToInt32(notesDataGridView.SelectedRows[0].Cells[0].Value);
notesProjectIDTextBox.Text = notesDataGridView.SelectedRows[0].Cells[1].Value.ToString();
notesTextBox.Text = notesDataGridView.SelectedRows[0].Cells[2].Value.ToString();
}
private void removeNote_Click(object sender, EventArgs e)
{
// Confirm user wants to delete by asking "Are you sure?"
var confirmDelete = MessageBox.Show("Are you sure you want to delete this note? This action cannot be undone.",
"Confirm Delete",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning);
if (confirmDelete == DialogResult.Yes)
{
if (NoteID > 0)
{
SqlCommand cmd = new SqlCommand("DELETE FROM sfNotes WHERE Note_ID= #Note_ID", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Note_ID", this.NoteID); // #Note_ID equals "this" NoteID that I clicked on
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Note is successfully deleted from the system", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information);
// now update/REFRESH the database so it shows the new record
GetProjectsDataset();
GetNotesDataset();
// reset form controls
ResetFormControls();
}
else
{
MessageBox.Show("Please select a note to delete", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
}
}
private void searchProjectsButton_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("SELECT * FROM sfProjects WHERE Project_ID= #Project_ID", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Project_ID", searchProjectsTextBox.Text); // maps #Project_ID to the search projects textbox
con.Open();
cmd.ExecuteNonQuery();
con.Close();
DataTable dtS = new DataTable();
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
dtS.Load(sdr);
con.Close();
dataGridView.DataSource = dtS;
// Automatically resizes the columns to fit the data grid view
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
// reset form controls
ResetFormControls();
}
private void searchNotesButton_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("SELECT * FROM sfNotes WHERE Project_ID= #Project_ID", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Project_ID", searchNotesTextBox.Text); // maps #Project_ID to the search projects textbox
con.Open();
cmd.ExecuteNonQuery();
con.Close();
DataTable dtS = new DataTable();
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
dtS.Load(sdr);
con.Close();
notesDataGridView.DataSource = dtS;
// Automatically resizes the columns to fit the data grid view
notesDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
notesDataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
// reset form controls
ResetFormControls();
}
}
}
This is the section that the error is happening:
// Filter the notes grid to only show notes for the row the user clicks
SqlCommand cmd = new SqlCommand("SELECT * FROM sfNotes WHERE Project_ID_Backend= #Project_ID_Backend", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Project_ID_Backend", this.ProjectIDBackend);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
SOLUTION: The problem was that I didn't "refresh" the database in SSMS after saving it.

Check the exception documentation: https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlexception?view=dotnet-plat-ext-3.1
The exception that is thrown when SQL Server returns a warning or error.
And the message:
Gets a message that describes the current exception
So the exception indicates that the query was executed on the database and that message is what the database returned. This leads me to believe one of two things.
Wrong connection string
You have made the change on a database that is different from the one your application connected to. A dev or test instance that you have not updated yet
You hand a pending transaction
You have run the script within a transaction that you have not committed.
Open a management studio and connect to the database that your application connects to. Try to execute the query.
Also check the profile you are building/running the application. Maybe it's release and you have transformed the connection string

Related

After Update using ExecuteNonQuery runs, changes in database are not registered

I am trying to create a CRUD application in which I made a movie selector. My only problem is that my "update" button is not updating data.
Button handler code is executing but not updating data, and also not updating the database.
Furthermore, it is showing a dialog box "(Movie Record Updated)"
SqlConnection myConn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\Final Project\CineMagic\MovieDatabase.mdf;Integrated Security=True");
private void updateMovieBtn_Click(object sender, EventArgs e)
{
if (Convert.ToInt32(nameBox.Text.Trim().Length) > 0)
{
try
{
myConn.Open();
SqlCommand myComnd = new SqlCommand(#"UPDATE ListTable SET Quality=#quality, Rating=#rating, Type=#type, Director=#director, ReleasedIn=#released WHERE Name=#name", myConn);
myComnd.CommandType = CommandType.Text;
myComnd.Parameters.AddWithValue("#name", nameBox.Text);
myComnd.Parameters.AddWithValue("#quality", qualityBox.Text);
myComnd.Parameters.AddWithValue("#rating", ratingBox.Text);
myComnd.Parameters.AddWithValue("#type", typeBox.Text);
myComnd.Parameters.AddWithValue("#director", directorBox.Text);
myComnd.Parameters.AddWithValue("#released", releasedBox.Text);
myComnd.ExecuteNonQuery();
myConn.Close();
MessageBox.Show("Movie Record Updated.", "Updated Successfully", MessageBoxButtons.OK, MessageBoxIcon.Information);
display_data();
resetFormControls();
}
catch (Exception myExc)
{
MessageBox.Show(myExc.Message);
}
}
else
{
MessageBox.Show("Select a record to update.", "Select...", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

How to access DataGridView from another Winform and show its data in TextBox

I have 2 Forms, both forms have separate datagridview. In form 1 I have a data entry form where multiple text fields are there. In Form1, I want Doctor textfield to get data as I enter from datagridview2 (column 1 Dr.Name) that is in Form2 and keep data in Docotr filed and Fees should be kept in Fees textbox related to that Dr. who is in Docotor field.
How can I do that?
These are the codes of datagridview2 & this datagridview2 shoud be called when the user goes on Docotr Textbox filed.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace AhsanHospital.Forms
{
public partial class DoctorDetailsForm : Form
{
public DoctorDetailsForm()
{
InitializeComponent();
}
int Doctor_ID;
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\db\MyDB.mdf;Integrated Security=True");
private void btnSave_Click(object sender, System.EventArgs e)
{
if (txtDoctorName.Text == "")
{
MessageBox.Show("Please insert Docotr Name", "Empty Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
txtDoctorName.Focus();
}
else
{
SqlCommand cmd = new SqlCommand("Insert Into Doctor_Details Values (#DrName,#DrDegree,#DrTiming,#DrMobile,#DrAddress,#DrFees )", conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#DrName", txtDoctorName.Text);
cmd.Parameters.AddWithValue("#DrDegree", txtDoctorDegree.Text);
cmd.Parameters.AddWithValue("#DrTiming", txtDoctorTiming.Text);
cmd.Parameters.AddWithValue("#DrMobile", txtDoctorMobile.Text);
cmd.Parameters.AddWithValue("#DrAddress", txtDoctorAddress.Text);
cmd.Parameters.AddWithValue("#DrFees", txtDoctroFees.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("New Doctor Added Successfully", "Doctor Added", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtDoctorName.Focus();
GetPatientRecord();
ClearFields();
}
}
private void GetPatientRecord()
{
SqlCommand command = new SqlCommand("SELECT * FROM Doctor_Details ORDER BY DoctorId", conn);
DataTable dt = new DataTable();
conn.Open();
SqlDataReader sdr = command.ExecuteReader();
dt.Load(sdr);
conn.Close();
dgvDoctorDetails.DataSource = dt;
}
private void ClearFields()
{
Doctor_ID = 0;
txtDoctorid.Clear();
txtDoctorName.Clear();
txtDoctorAddress.Clear();
txtDoctorDegree.Clear();
txtDoctorMobile.Clear();
txtDoctorTiming.Clear();
txtDoctroFees.Clear();
txtDoctorName.Focus();
btnSave.Enabled = true;
}
private void DoctorDetailsForm_Load(object sender, EventArgs e)
{
GetPatientRecord();
}
private void DoctorDetailsForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
SendKeys.Send("{TAB}");
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (txtDoctorName.Text == "" || txtDoctroFees.Text == "")
{
MessageBox.Show("Please fill all the required fields", "Empty Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
txtDoctorName.Focus();
}
else
{
SqlCommand cmd = new SqlCommand("UPDATE Doctor_Details SET Doctor_Name=#DrName,Doctor_Degree=#DrDegree,Doctor_Timing=#DrTiming,Doctor_Mobile=#DrMobile,Doctor_Address=#DrAddress,Doctor_Fees=#DrFees WHERE DoctorId =#DrID", conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#DrName", txtDoctorName.Text);
cmd.Parameters.AddWithValue("#DrDegree", txtDoctorDegree.Text);
cmd.Parameters.AddWithValue("#DrTiming", txtDoctorTiming.Text);
cmd.Parameters.AddWithValue("#DrMobile", txtDoctorMobile.Text);
cmd.Parameters.AddWithValue("#DrAddress", txtDoctorAddress.Text);
cmd.Parameters.AddWithValue("#DrFees", txtDoctroFees.Text);
cmd.Parameters.AddWithValue("#DrID", this.Doctor_ID);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Doctor Details Updated Successfully", "Doctor Updated", MessageBoxButtons.OK, MessageBoxIcon.Information);
GetPatientRecord();
ClearFields();
txtDoctorName.Focus();
}
}
private void dgvDoctorDetails_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
btnSave.Enabled = false;
Doctor_ID = Convert.ToInt32(dgvDoctorDetails.SelectedRows[0].Cells[0].Value);
txtDoctorid.Text = dgvDoctorDetails.SelectedRows[0].Cells[0].Value.ToString();
txtDoctorName.Text = dgvDoctorDetails.SelectedRows[0].Cells[1].Value.ToString();
txtDoctorDegree.Text = dgvDoctorDetails.SelectedRows[0].Cells[2].Value.ToString();
txtDoctorTiming.Text = dgvDoctorDetails.SelectedRows[0].Cells[3].Value.ToString();
txtDoctorMobile.Text = dgvDoctorDetails.SelectedRows[0].Cells[4].Value.ToString();
txtDoctorAddress.Text = dgvDoctorDetails.SelectedRows[0].Cells[5].Value.ToString();
txtDoctroFees.Text = dgvDoctorDetails.SelectedRows[0].Cells[6].Value.ToString();
}
private void btnClear_Click(object sender, EventArgs e)
{
ClearFields();
}
}
}
Use contractor and pass value from 1 form to other
in constructor you can pass specific value or you may pass object
I have figured it out. I simply changed Dr. Name field from TextBox to ComboBox & created an Event called SelectedIndexChangedon Dr. Name ComboBox.
private void cmbDoctorName_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbDoctorName.Text=="")
{
}
else
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Doctor_Fees FROM Doctor_Details WHERE Doctor_Name='" + cmbDoctorName.SelectedItem.ToString() + "' ";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
txtCharges.Text = dr["Doctor_Fees"].ToString();
}
conn.Close();
}
}

how to insert a datagridview value to database on button click in c#

I have two controls in my winform ,that is textboxes and datagridview .textboxes data entered by user save in one table(purchase) and datagridview data entered is save in another table (purchasedetail).My problem is textboxes values are saving in purchase table but datagridview values are not saving to database.
here is my save button code:
private void SAVE(object sender, EventArgs e)
{
try
{
con.Open();
cmd = new SqlCommand("insert into Purchase(purchase_id,purchase_date,ref_no,total,total_wrds) values(#purchase_id,#purchase_date,#ref_no,#total,#total_wrds)", con);
cmd.Parameters.AddWithValue("#purchase_id", textid.Text);
cmd.Parameters.AddWithValue("#purchase_date", dateTimePicker1.Value);
cmd.Parameters.AddWithValue("#ref_no", textrno.Text);
cmd.Parameters.AddWithValue("#total", texttotal.Text);
cmd.Parameters.AddWithValue("#total_wrds", textinwrds.Text);
cmd.ExecuteNonQuery();
foreach (DataGridViewRow row in datagrid.Rows)
{
if (!row.IsNewRow)
{
using(SqlCommand cmd11 = new SqlCommand("insert into Purchasedetail(product_id, product_name,qty,price,tax,discount,total)values(#product_id, #product_name,#qty,#price,#tax,#discount,#total)", con))
{
cmd11.Parameters.AddWithValue("#product_id", row.Cells[0].Value);
cmd11.Parameters.AddWithValue("#product_name", row.Cells[1].Value);
cmd11.Parameters.AddWithValue("#qty", row.Cells[2].Value);
cmd11.Parameters.AddWithValue("#price", row.Cells[3].Value);
cmd11.Parameters.AddWithValue("#tax", row.Cells[4].Value);
cmd11.Parameters.AddWithValue("#discount", row.Cells[5].Value);
cmd11.Parameters.AddWithValue("#total", row.Cells[6].Value);
cmd11.ExecuteNonQuery();
datagrid.Refresh();
//row.ReadOnly = true;
//clm.ReadOnly = true;
MessageBox.Show("Added Sucessfully", "OUTPUT", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
I assume you want to save your DataGrid table to a table in your database. With this answer I recommend you to work with your data in datagrid, not textboxes, if it is not very necessary.
First I am explaining the code.
Since your temporary DG table will be "added" you need to clear it first. Then turn your itemssource into a table and it is ready to be saved. Use an adapter to update the table.
try
{
SqlCommand ClearTableCommand = new SqlCommand("delete from " + CurrentTableName + ";", myconnection);
ClearTableCommand.ExecuteNonQuery();
DataTable myDT;
DataView myview;
myview = (DataView)dataGrid1.ItemsSource;
myDT = myview.ToTable(CurrentTableName);
using (SqlDataAdapter Adapter1 = new SqlDataAdapter("select * from " + CurrentTableName + "", myconnection))
{
Adapter1.UpdateCommand = new SqlCommandBuilder(Adapter1).GetUpdateCommand(true);
Adapter1.AcceptChangesDuringFill = false;
Adapter1.AcceptChangesDuringUpdate = true;
Adapter1.Update(myDT);
}
}
catch (Exception ex)
{
System.windows.MessageBox.Show(ex.Message);
}

Refreshing the combobox after inserting data in mysql c#

Hello so i want to refresh my combobox after i add or delete data from it now if i add data it doesnt get refreshed i have to rerun the program to see the changes but i want to get it refresh in the time i add the data..
the code when i add data:
private void button5_Click(object sender, EventArgs e)
{
MySqlConnection dataConnection = new MySqlConnection();
dataConnection.ConnectionString = "datasource=localhost;port=3306;username=root;password=";
dataConnection.Open();
MySqlTransaction transakcija = dataConnection.BeginTransaction();
MySqlCommand dataCommand = new MySqlCommand();
dataCommand.Connection = dataConnection;
dataCommand.Transaction = transakcija;
try
{
dataCommand.CommandText = "Insert INTO filmi.film (film) VALUES ('" + this.tB_Dodaj.Text + "')";
dataCommand.CommandType = CommandType.Text;
dataCommand.ExecuteNonQuery();
transakcija.Commit();
MessageBox.Show("You added a new movie!");
}
catch (Exception eks)
{
transakcija.Rollback();
MessageBox.Show("Movie couldnt be added!!\n" + eks.Message);
}
finally
{
dataCommand.Connection.Close();
}
}
and with each insert the data gets displayed in the combobox but only when i rerun the program
this is how i fill combobox:
void Fillcombo()
{
string constring = "datasource=localhost;port=3306;username=root;password=";
string Query = "SELECT * FROM filmi.film ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string sName = myReader.GetString("film");
comboBox1.Items.Add(sName);
comboBox2.Items.Add(sName);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
i have to rerun the program to see the changes but i want to get it
refresh in the time i add the data..
I suspect that you are calling the Fillcombo() method in Form_Load event handler.
if you want to update the combobox for every insert and delete operations in your table you need to call Fillcombo() immediatly after executing the command.
Try This:
int status = dataCommand.ExecuteNonQuery();
transakcija.Commit();
if(status > 0)
{
Fillcombo();
MessageBox.Show("You added a new movie!");
}
in your FillCombo clear the items before adding the new items to remove the duplicates.
comboBox1.Items.Clear(); //add this statetement before adding items
comboBox2.Items.Clear(); //add this statetement before adding items
while (myReader.Read())
{
string sName = myReader.GetString("film");
comboBox1.Items.Add(sName);
comboBox2.Items.Add(sName);
}
ADO.NET object works in a disconnected state, so, adding a record to your datatable doesn't automatically shows up in your combo. You need to call again FillCombo, (clearing the items already in combos, going again to the database to retrieve every record again, adding them to your comboboxes) or just simply adding the film to your already filled combos as a single item
Also pay attention to Sql Injection (use always a parameterized query)
private void button5_Click(object sender, EventArgs e)
{
string conString = "datasource=localhost;port=3306;username=root;password=";
string cmdText = "Insert INTO filmi.film (film) VALUES (#film)";
using(MySqlConnection dataConnection = new MySqlConnection(conString))
using(MySqlCommand dataCommand = new MySqlCommand(cmdText, dataConnection))
{
try
{
dataConnection.Open();
dataCommand.Parameters.AddWithValue("#film", this.tB_Dodaj.Text);
// If ExecuteNonQuery returns a value > 0 then your record has been inserted
// Just add the name of the film to the two combos
if(dataCommand.ExecuteNonQuery() > 0)
{
MessageBox.Show("You added a new movie!");
comboBox1.Items.Add(this.tB_Dodaj.Text);
comboBox2.Items.Add(this.tB_Dodaj.Text);
}
}
catch(Exception ex)
{
MessageBox.Show("Fail to add a new movie! " + ex.Message);
}
}
}
As a last note, watch carefully your fillcombo method. You don't close and dispose the connection.

CombBox is not populating the ValueMember Properly from MySQL in C#

I have two combobox in my form, using a mysql connection to a remote server. The first combobox populated nicely. However, I need the indexid since that is a foreign key to populate a second combobox. Based on the selection, it will change the data in the second combo (for the xample, i the first combo is for car makes, then the models of each make gets filled, so if I choose Nissan, the models will then have Altima, Maxima, Sentra, ... but if I chose Toyota, the combo will then show Corolla, Camry, Prius, ...)
My foreign key is always -1 for some reason. I am using the selectindex change method, but it keeps crashing/ bc the value is always -1.
I am very new to MySQL in C# and eager to learn. Any help is appreciated. The code is below.
private void cboMake_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboMake.SelectedIndex >= 0)
cboModel.Enabled = true;
else
cboModel.Enabled = false;
// get the foreign key value of the model id to get the make for each brand to populate here
// MessageBox.Show(cboModel.ValueMember);
// right now selectindex always shows -1. why?
// if it changes, you need to then enable the right cbo, else, disable.
// but also, you need the mid, fk, so you can then do a new sql statement with the where clause to populate it.
int fk = cboModel.SelectedIndex;
string connStr = "server=123.456.7.8;user=root;database=car;port=3306; password=nowayjose";
MySqlConnection conn = new MySqlConnection(connStr);
try
{
string sql = "SELECT * FROM cs_model WHERE mid='fk'";
MySqlCommand cmd = new MySqlCommand(sql, conn);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
cboMake.DataSource = dt;
cboMake.DisplayMember = "model";
cboMake.ValueMember = "mmid";
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "MySQL Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
conn.Close();
}
private void frmMain_Load(object sender, EventArgs e)
{
string connStr = "server=123.456.7.8;user=root;database=car;port=3306; password=nowayjose";
MySqlConnection conn = new MySqlConnection(connStr);
try
{
string sql = "SELECT * FROM cs_make";
MySqlCommand cmd = new MySqlCommand(sql, conn);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
cboMake.DataSource = dt;
cboMake.DisplayMember = "make";
cboMake.ValueMember = "mid";
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "MySQL Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
conn.Close();
}
Correct me if I'm wrong, but considering code provided, just a guess :
private void cboMake_SelectedIndexChanged(object sender, EventArgs e)
{
int fk = cboModel.SelectedIndex; // ?????
.....
}
You access here cboModel, which is not that one whom item was actually selected. At least lookin on event name cboMake_SelectedIndexChanged, seems to me that you should look on cboMake selected index.
Hope this helps.
private void cboMake_SelectedIndexChanged(object sender, EventArgs e)
{
int foreignKey = (int)cboMake.SelectedIndex +1; // i forgot to cast the int from string since the database was tinyint, it still returns string in c#
string fk = foreignKey.ToString(); // since i need the string for the query, back it goes, but i needed to do arithmetic
string connStr = "server=10.18.30.1;user=notroot;database=car;port=3306;password=password";
MySqlConnection conn = new MySqlConnection(connStr);
try
{
string sql = "SELECT * FROM cs_model WHERE mid=" + fk; // forgot to escape out of the string (used to php $var style within double quotes)
MySqlCommand cmd = new MySqlCommand(sql, conn);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
cboModel.DataSource = dt; // i had cboModel by a silly mistake
cboModel.DisplayMember = "model";
cboModel.ValueMember = "mmid";
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "MySQL Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
conn.Close();
}

Categories