I am trying to create add button in the gridview. I have 3 joining tables and 3 drop-down lists.
That is the error that I get:
Additional information: Invalid column name 'Quotation_Number'. Invalid column name 'Customer_Name'. Invalid column name 'Machine_Model'.
Can you help me? I think the problem is in the insert statement
Thanks
public void userSales()
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT SalesActivity.Activity_ID, SalesActivity.Date, SalesActivity.Quatation_Number, CUSTOMER.Customer_Name, PRODUCTS.Machine_Model, SalesActivity.Quantity, SalesActivity.valueGBR, SalesActivity.valueEUR, SalesActivity.Rate, SalesActivity.weightedValue, STATUS.Status, SalesActivity.estDecisionDate, SalesActivity.PromisedDeliveryDate FROM SalesActivity INNER JOIN CUSTOMER ON SalesActivity.Customer_ID = CUSTOMER.Customer_ID INNER JOIN PRODUCTS ON SalesActivity.Product_ID = PRODUCTS.Product_ID INNER JOIN STATUS ON SalesActivity.Status_ID = STATUS.Status_ID ", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow()); // if record not found then returning a blank table structure
GridView1.DataSource = ds;
GridView1.DataBind();
int columncount = GridView1.Rows[0].Cells.Count;
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
GridView1.Rows[0].Cells[0].Text = "No Records Found";
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex; //this open new index that is edit mode
userSales();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1; //after cancel button want go to one index back that's y -1
userSales();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtActivity = (TextBox)GridView1.FooterRow.FindControl("ftxtActivity");
TextBox ftxtDate = (TextBox)GridView1.FooterRow.FindControl("ftxtDate");
TextBox ftxtQno = (TextBox)GridView1.FooterRow.FindControl("ftxtQno");
DropDownList fddlCName = GridView1.FooterRow.FindControl("fddlCName") as DropDownList;
DropDownList fddlMmodel = GridView1.FooterRow.FindControl("fddlMmodel") as DropDownList;
TextBox ftxtQuantity = (TextBox)GridView1.FooterRow.FindControl("ftxtQuantity");
TextBox ftxtvalueGBR = (TextBox)GridView1.FooterRow.FindControl("ftxtvalueGBR");
TextBox ftxtvalueEUR = (TextBox)GridView1.FooterRow.FindControl("ftxtvalueEUR");
TextBox ftxtRate = (TextBox)GridView1.FooterRow.FindControl("ftxtRate");
TextBox ftxtweightedValue = (TextBox)GridView1.FooterRow.FindControl("ftxtweightedValue");
DropDownList fddlStatus = GridView1.FooterRow.FindControl("fddlStatus") as DropDownList;
TextBox ftxtestDecisionDate = (TextBox)GridView1.FooterRow.FindControl("ftxtestDecisionDate");
TextBox ftxtPromisedDeliveryDate = (TextBox)GridView1.FooterRow.FindControl("ftxtPromisedDeliveryDate");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO SalesActivity(Activity_ID, Date, Quotation_Number, Customer_Name, Machine_Model,Quantity, valueGBR, valueEUR, Rate, weightedValue, Status, estDecisionDate, PromisedDeliveryDate) VALUES(#Activity_ID, #Date, #Quotation_Number, #Customer_Name, #Machine_Model, #Quantity, #valueGBR, #valueEUR, #Rate, #weightedValue, #Status, #estDecisionDate, #PromisedDeliveryDate)", con);
cmd.Parameters.AddWithValue("#Activity_ID", txtActivity.Text.Trim());
cmd.Parameters.AddWithValue("#Date", ftxtDate.Text.Trim());
cmd.Parameters.AddWithValue("#Quotation_Number", ftxtQno.Text.Trim());
cmd.Parameters.AddWithValue("#Customer_Name", fddlCName.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Machine_Model", fddlMmodel.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Quantity", ftxtQuantity.Text.Trim());
cmd.Parameters.AddWithValue("#valueGBR", ftxtvalueGBR.Text.Trim());
cmd.Parameters.AddWithValue("#valueEUR", ftxtvalueEUR.Text.Trim());
cmd.Parameters.AddWithValue("#weightedValue",ftxtweightedValue.Text.Trim());
cmd.Parameters.AddWithValue("#Rate", ftxtRate.Text.Trim());
cmd.Parameters.AddWithValue("#Status", fddlStatus.SelectedItem.Text);
cmd.Parameters.AddWithValue("#estDecisionDate", ftxtestDecisionDate.Text.Trim());
cmd.Parameters.AddWithValue("#PromisedDeliveryDate", ftxtPromisedDeliveryDate.Text.Trim());
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
userSales();
Response.Write("<script language=javascript>alert('" + txtActivity.Text + "'+'Sale Details inserted successfully');</script>");
}
else
{
Response.Write("<script language=javascript>alert('" + txtActivity.Text + "'+' Sale Details not inserted');</script>");
}
}
}
Your Select Statement is executing this...
SELECT SalesActivity.Activity_ID
,SalesActivity.DATE
,SalesActivity.Quatation_Number
,CUSTOMER.Customer_Name
,PRODUCTS.Machine_Model
,SalesActivity.Quantity
,SalesActivity.valueGBR
,SalesActivity.valueEUR
,SalesActivity.Rate
,SalesActivity.weightedValue
,STATUS.STATUS
,SalesActivity.estDecisionDate
,SalesActivity.PromisedDeliveryDate
FROM SalesActivity
INNER JOIN CUSTOMER ON SalesActivity.Customer_ID = CUSTOMER.Customer_ID
INNER JOIN PRODUCTS ON SalesActivity.Product_ID = PRODUCTS.Product_ID
INNER JOIN STATUS ON SalesActivity.Status_ID = STATUS.Status_ID
Machine_Model and Customer_Name do not belong to SalesActivity Table, they belong to Products and Customer respectively. And your issue with Quotation_Number is Quatation_Number in the select.
change this...
SqlCommand cmd = new SqlCommand("INSERT INTO SalesActivity(Activity_ID, Date, Quotation_Number, Customer_Name, Machine_Model,Quantity, valueGBR, valueEUR, Rate, weightedValue, Status, estDecisionDate, PromisedDeliveryDate) VALUES(#Activity_ID, #Date, #Quotation_Number, #Customer_Name, #Machine_Model, #Quantity, #valueGBR, #valueEUR, #Rate, #weightedValue, #Status, #estDecisionDate, #PromisedDeliveryDate)", con);
to this...
SqlCommand cmd = new SqlCommand("INSERT INTO SalesActivity(Activity_ID, Date, Quatation_Number,Quantity, valueGBR, valueEUR, Rate, weightedValue, estDecisionDate, PromisedDeliveryDate) VALUES(#Activity_ID, #Date, #Quotation_Number, #Quantity, #valueGBR, #valueEUR, #Rate, #weightedValue, #estDecisionDate, #PromisedDeliveryDate)", con);
and remove the following lines...
cmd.Parameters.AddWithValue("#Customer_Name", fddlCName.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Machine_Model", fddlMmodel.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Status", fddlStatus.SelectedItem.Text);
The insert should now work.
Related
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
I have a function to load gridview1 and i want to view grid view button coloumns that are at coloumn 7 and 8 only when M_Status from query is equal to 1 , their are multiple records against m_id=2 having m_status equal to 2 , 1, 3 but i want to show approve and deny buttons only against m_id =1
private void loadvisitor()
{
con1 = new SqlConnection(constring1);
string seelctquery = "SELECT M_Status,d.MD_ID , d.MD_Visitor_Name,d.MD_Visitor_Cell, d.MD_Visitor_Company,s.M_StatusName, p.purpose_name , m.M_DateTime FROM Vms_Meeting M left outer join Vms_MeetingD d on m.M_ID= d.M_ID left outer join Vms_Purpose p on m.Purpose_ID= p.purpose_id inner join vms_MeetingStatus as s on d.M_Status = s.M_Status WHERE m.M_ID=2 order by m.M_ID desc;";
da = new SqlDataAdapter(seelctquery, con1);
SqlCommand cmd = new SqlCommand(seelctquery, con1);
if (con1.State == ConnectionState.Closed)
{
con1.Open();
}
dr = cmd.ExecuteReader();
ds = new DataSet();
da.Fill(ds);
cmd.ExecuteNonQuery();
GridView1.DataSource = ds;
GridView1.DataBind();
if (dr.HasRows)
{
while (dr.Read())
{
string stid = (string)dr["M_Status"];
if (stid == "1")
{
}
}
}
con1.Close();
}
I have 2 datagridview controls in a Windows Forms application.
I would like to get the info of a person when I select first datagridview cell or row to next datagridview:
try
{
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
con.Open();
adap3 = new SqlDataAdapter(#"SELECT Date,Attendance,Remarks FROM dailyattendance where employee_id='"+DailyGV.CurrentRow+"'", con);
ds3 = new DataSet();
adap3.Fill(ds3, "dailyattendance");
dataGridView1.DataSource = ds3.Tables[0];
}
Im trying the above code. But it's not working.
I'm not too sure what DailyGV.CurrentRow is but basically you can use the RowHeaderMouseClick...see MSDN documentation. To use it, hook an event handler to it when initializing the form components (you can use VS designer as well...
dataGridView1.RowHeaderMouseClick += dataGridView1_RowHeaderMouseClick;
void dataGridView1_RowHeaderMouseClick(
object sender, DataGridViewCellMouseEventArgs e)
{
}
this event handler will get fired everytime you select a row header in the DataGridView control which will pass information about the event through an instance of the DataGridViewCellMouseEventArgs class (see MSDN documentation). This argument has a RowIndex property that provides the index of the row clicked which you can use to retrieve the values of the cells in that row...including the person id (if provided)...for example...
void dataGridView1_RowHeaderMouseClick(
object sender, DataGridViewCellMouseEventArgs e)
{
string personId = dataGridView1.Rows[e.RowIndex].Cells["PersonId"].Value;
//TODO: implement your own query to retrieve data for that person id
}
notice that you need to provide a proper column name when access the cells collection indexer...Cells["columnName"]
I will not give any description about the solution because Leo and Arsalan Bhatti has already suggested the solution. I am just telling you how your code should looks like and how it should be written.
string connectionString = consettings.ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
con.Open();
string empID = DailyGV.CurrentRow.Cells["employee_id"].Value.ToString();
SqlCommand Cmd = con.CreateCommand();
Cmd.CommandText = "SELECT Date,Attendance,Remarks FROM dailyattendance where employee_id=#employee_id";
Cmd.Parameters.Add("#employee_id", SqlDbType.Int).Value = Int32.Parse(empID);
adap3 = new SqlDataAdapter(Cmd);
DataTable dt = new DataTable();
adap3.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
catch
{}
}
try
{
cn.Open();
string query = "select employee_id,Employee_Name,Image_of_Employee from Employee_Details where employee_id='" + dataGridView1.SelectedCells[0].Value.ToString() + "'";
SqlCommand cmd = new SqlCommand(query, cn);
SqlDataReader sdr;
sdr = cmd.ExecuteReader();
if (sdr.Read())
{
string aa = (string)sdr["employee_id"];
string bb = (string)sdr["employee_name"];
txtEmployeeID.Text = aa.ToString();
txtnameofemployee.Text = bb.ToString();
byte[] img=(byte[])sdr["Image_of_employee"];
MemoryStream ms=new MemoryStream(img);
ms.Seek(0,SeekOrigin.Begin);
pictureBox1.Image=Image.FromStream(ms); cn.Close();
}
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
You are passing the current row's index as employee id in SELECT query. Pass employee id for the selected record. Then it will work fine.
I am trying to select film by using on select command, print the title in a label once selected.. that works well.
next part is the selected film will then decrement 1 from the database stock on button click. This is where I think I am getting confused, its showing no errors until the button click takes place.
C# code for update query
protected void Button2_Click(object sender, EventArgs e)
{
var myquery = string.Format("UPDATE DVD SET Stock = Stock - 1");
da.InsertCommand = new OleDbCommand("INSERT INTO DVD (Stock) VALUES (#MessageLabel)", conn);
{
da.InsertCommand.Parameters.AddWithValue("#Stock", MessageLabel.Text);
conn.Open();
da.InsertCommand.ExecuteNonQuery();
using (OleDbCommand cmd = new OleDbCommand(myquery, conn))
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
}
Previous code for select event
public void Latest_DVD()
{
{
using (OleDbDataAdapter dataquer = new OleDbDataAdapter("SELECT Title,Category,Director,Stock,Year FROM DVD ", conn))
{
dataquer.Fill(dt);
}
}
DG_Latest.ShowHeader = true;
DG_Latest.DataSource = dt;
DG_Latest.DataBind();
conn.Close();
conn.Dispose();
}
protected void Latest_DVD_SelectedIndexChanged(Object sender, EventArgs e)
{
GridViewRow row = DG_Latest.SelectedRow;
MessageLabel.Text = "You selected to rent " + row.Cells[1].Text + ".";
}
so I am thinking I have the query wrong and possibly nor retrieve the update from the label but maybe the on select its self... I am not sure through.
the error it is showing is
Data type mismatch in criteria expression.
just after the connection is open
As #afzalulh said, remove the insert part. And change myquery string to be:
var myquery = string.Format("UPDATE DVD SET Stock = Stock - 1 WHERE Title = #Title");
var row = DB_Latest.SelectedRow;
var title = row.Cells[0].Text;
var cmd = new OleDbCommand(myquery, conn);
cmd.Parameters.AddWithValue("#Title", title);
With that, you only update Stock for the selected DVD title only. Without adding WHERE clause, the query will decrease stock for all DVDs.
You want to update stock, there's no need to insert. I believe this is what you want:
protected void Button2_Click(object sender, EventArgs e)
{
var myquery = string.Format("UPDATE DVD SET Stock = Stock - 1");
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(myquery, conn))
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
EDIT: myquery should include WHERE as suggested by har07. Otherwise it will reduce all DVD's stock by 1.
I got a ComboBox with a table as data source, ID as a value member and a name as a display member.
Selecting a name from the ComboBox should populate 6 TextBoxes with data.
Exception:
The data type is not valid for the boolean operation. [ Data type (if known) = int,Data type (if known) = nvarchar ]
Code:
void FillComboBox()
{
//Fill Combo Box
SqlCeDataAdapter da = new SqlCeDataAdapter(" SELECT CustomerID, Name FROM Customers", clsMain.con);
DataSet ds = new DataSet();
da.Fill(ds);
cBox1.DataSource = ds.Tables[0];
cBox1.ValueMember = "CustomerID";
cBox1.DisplayMember = "Name";
}
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
clsMain.con.ConnectionString = #"Data Source=|DataDirectory|\Database\Sales.sdf";
clsMain.con.Open();
FillComboBox();
}
private void btnSave_Click(object sender, EventArgs e)
{
//Save Button
SqlCeCommand cmd = new SqlCeCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = " INSERT INTO Customers (Name, Phone1, Phone2, Address, Notes) VALUES (#Name, #Phone1, #Phone2, #Address, #Notes) ";
cmd.Connection = clsMain.con;
cmd.Parameters.AddWithValue("#Name", txt2.Text.Trim());
if (txt3.Text != "")
{
cmd.Parameters.AddWithValue("#Phone1", Convert.ToInt32(txt3.Text));
}
else
{
cmd.Parameters.AddWithValue("#Phone1", Convert.DBNull);
}
if (txt4.Text != "")
{
cmd.Parameters.AddWithValue("#Phone2", Convert.ToInt32(txt4.Text));
}
else
{
cmd.Parameters.AddWithValue("#Phone2", Convert.DBNull);
}
cmd.Parameters.AddWithValue("#Address", txt5.Text.Trim());
cmd.Parameters.AddWithValue("#Notes", txt6.Text.Trim());
cmd.ExecuteNonQuery();
MessageBox.Show("Data stored.");
}
private void cBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (cBox1.SelectedIndex >= 0)
{
String Code = "SELECT * FROM Customers WHERE CustomerID=" + cBox1.SelectedValue.ToString();
SqlCeDataAdapter da = new SqlCeDataAdapter(Code, clsMain.con);
DataSet ds = new DataSet();
da.Fill(ds);
txt1.Text = ds.Tables[0].Rows[0]["CustomerID"].ToString();
txt2.Text = ds.Tables[0].Rows[0]["Name"].ToString();
txt3.Text = ds.Tables[0].Rows[0]["Phone1"].ToString();
txt4.Text = ds.Tables[0].Rows[0]["Phone2"].ToString();
txt5.Text = ds.Tables[0].Rows[0]["Address"].ToString();
txt6.Text = ds.Tables[0].Rows[0]["Notes"].ToString();
}
}
Table Details:
To follow up on my comment (with the caveat that I have never worked with SQL CE, but I'm pretty sure (99.9%) that this is correct).
In you SQL query string, you surround the customer id with single quotes ('). You use single quotes in SQL ("nomral" SQL at least) for character (char\varchar etc) and date values. You pass numeric values without single quotes.
You didn't indicate what line was giving you the exception, but based on the table structure and what you are doing (you gave good detail in your question, by the way), it seems that the error message is telling you that you're trying to compare an int to a varchar, and that's not allowed (because they are different data types, as the error indicates).
To resolve this, simply remove the single quotes from the value in your WHERE clause and construct your query as follows:
String Code = "SELECT * FROM Customers WHERE CustomerID=" + cBox1.SelectedValue;
Thank you, Its working for me.
I am having some customers name in comboBox2. Based on the selected name textbox will return CustomerID and Date of Allocation values.
Following are the code for that:
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if(comboBox2.SelectedIndex>0)
{
con = new SqlCeConnection(s);
con.Open();
string code = "select CustomerID,Date_of_Allocation from lockerdetails
where CustomerName='" + comboBox2.SelectedValue.ToString() + "'";
SqlCeDataAdapter da = new SqlCeDataAdapter(code, con);
SqlCeCommandBuilder cmd = new SqlCeCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds);
textBox1.Text = ds.Tables[0].Rows[0]["CustomerID"].ToString();
textBox5.Text = ds.Tables[0].Rows[0]["Date_of_Allocation"].ToString();
}
}
catch(SystemException se)
{
MessageBox.Show(se.Message);
}