I have 2 ListBoxes and five textBox. In ListBox_prod i want to retrieve all product (from PRODUCT table) and in Listbox_item i want to retrieve all Items corresponding to the selected Product (from PRODITEM table) on form load event. All the products have more than 1 items associated with them. Problem is with the Listbox_item as it is showing only 1 item. But I want all items to be displayed in Listbox_item when a particulat product is selected. getData() in class DBCommands actually causes the problem. Here's my code:
public partial class form_prodItems : Form
{
private DBCommands dBCommand;
public form_prodItems()
{
InitializeComponent();
listBx_prod.SelectedIndexChanged += new EventHandler(listBx_prod_selValChange);
listBx_item.SelectedIndexChanged += new EventHandler(listBx_item_selValChange);
}
private void form_prodItems_Load(object sender, EventArgs e)
{
// ...
refresh_listBx_prod("PRODUCT", this.listBx_prod, null, null);
refresh_listBx_prod("PRODITEM", this.listBx_item, listBx_prod.ValueMember, listBx_prod.SelectedValue.ToString());
}
private void listBx_item_selValChange(object sender, EventArgs e) // causing problem
{
if (listBx_item.SelectedValue != null)
showPrice("PRODITEM", listBx_item.ValueMember, listBx_item.SelectedValue.ToString());
}
private void listBx_prod_selValChange(object sender, EventArgs e)
{
if(listBx_prod.SelectedValue != null)
refresh_listBx_prod("PRODITEM", this.listBx_item, listBx_prod.ValueMember, listBx_prod.SelectedValue.ToString());
}
private void showPrice(string tblName,string where_column ,string where_val)
{
DataSet ds;
ds = dBCommand.getData("select * from " + tblName + " WHERE " + where_column + " = '" + where_val + "'");
DataRow col_val = ds.Tables[0].Rows[0];
txtBox_12oz.Text = col_val.ItemArray[3].ToString();
txtBox_16oz.Text = col_val.ItemArray[4].ToString();
txtBox_20oz.Text = col_val.ItemArray[5].ToString();
txtBox_1lbs.Text = col_val.ItemArray[6].ToString();
txtBox_2lbs.Text = col_val.ItemArray[7].ToString();
//ds.Clear();
}
private void refresh_listBx_prod(string tblName, ListBox listBox, string where_column, string where_val)
{
DataSet ds = new DataSet();
dBCommand = new DBCommands();
if (where_column == null)
{
ds = dBCommand.getData("SELECT * FROM " + tblName);
}
else
{
ds = dBCommand.getData("SELECT * FROM " + tblName + " WHERE " + where_column + " = " + where_val);
}
listBox.DataSource = ds.Tables[0];
// ds.Clear();
}
}
public class DBCommands
{
private SqlConnection conn;
private SqlDataAdapter dataAdapter;
private DataSet container;
public DataSet getData(string selectCmd)
{
container.Clear(); // I guess something needs to be fixed here some where..
conn = getConnection();
dataAdapter.SelectCommand = new SqlCommand(selectCmd, conn);
dataAdapter.Fill(container);
conn.Close();
return container;
}
private SqlConnection getConnection()
{
SqlConnection retConn = new SqlConnection("Data Source=" + Environment.MachineName + "; Initial Catalog=RESTAURANT; Integrated Security = TRUE");
retConn.Open();
return retConn;
}
}
Actually dataset flushes all data it had got from (SELECT * FROM PRODITEM where PRODUCT_id = '1') and shows data from the last executed query i-e (select * from proditem where item_id = 1)
Any suggestions..
my suggestion is trying to run the command via SqlCommand.
that way you will have better knowledge on what you get back.
use this example:
SqlCommand command = new SqlCommand(selectCmd, conn);
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
and modify it so you'll return a table as you need.
the reason i offer you this is that it's easy to use and you get immediate debug information that help you understand sql mistakes
Related
I'm trying to pull data from the database to DataGridView3, you can see it on the right column on image below. When i did debug, i saw that DataSet keeps correct values and on first try when i do cellClick on dataGrid1 it shows correct. But in subsequent attempts DataGridView3 does not display DataSet, although in debug there are correct values in DataSet. DataGridView3 display only header titles of tables, not records in database. Also when i click on this headers(thereby doing the sorting of rows) records appears. You can see this on picture 2. So problem is in DataGridView, which can't display data which is stored in him. I tried to use Update(), Refresh(), Show() methods on DataGridView3, but it's not helped.
using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.Windows.Forms;
namespace Lab3
{
public partial class Form1 : Form
{
private MySqlConnection connection = null;
private DataSet dataSet = null;
private DataSet dataSetOld = null;
private MySqlDataAdapter doctorDataAdapter = null;
private MySqlDataAdapter patientDataAdapter = null;
private MySqlDataAdapter appointmentDataAdapter = null;
public Form1()
{
InitializeComponent();
}
public void setConnection(MySqlConnection connection)
{
this.connection = connection;
}
//creating DataSet
private DataSet getDataSet()
{
if (dataSet == null)
{
dataSet = new DataSet();
dataSet.Tables.Add("Doctor");
dataSet.Tables.Add("Patient");
dataSet.Tables.Add("Appointment");
}
return dataSet;
}
//set connection with database
public MySqlConnection Connect(string host, int port, string database,
string username, string password)
{
string connStr = "Server=" + host + ";Database=" + database + ";port=" + port + ";User Id=" + username + ";password=" + password;
MySqlConnection connection = new MySqlConnection(connStr);
connection.Open();
return connection;
}
public void FillDataGridView1ByDoctors()
{
getDataSet().Tables["Doctor"].Clear();
doctorDataAdapter = new MySqlDataAdapter(
"SELECT * FROM Doctor", connection);
new MySqlCommandBuilder(doctorDataAdapter);
doctorDataAdapter.Fill(getDataSet(), "Doctor");
dataGridView1.DataSource = getDataSet().Tables["Doctor"];
this.dataGridView1.Columns["id_doctor"].Visible = false;
}
public void FillDataGridView2ByPatients()
{
getDataSet().Tables["Patient"].Clear();
patientDataAdapter = new MySqlDataAdapter(
"SELECT * FROM Patient", connection);
new MySqlCommandBuilder(patientDataAdapter);
patientDataAdapter.Fill(dataSet, "Patient");
dataGridView2.DataSource = getDataSet().Tables["Patient"];
this.dataGridView2.Columns["id_patient"].Visible = false;
dataGridView2.ClearSelection();
}
public void FillDataGridView3ByAppointment(string table, int id)
{
getDataSet().Tables["Appointment"].Reset();
if (table == "Doctor")
{
appointmentDataAdapter = new MySqlDataAdapter(
"SELECT patient.name_patient AS `Имя`, patient.surname_patient, appointment.datetime " +
"FROM patient, appointment, doctor " +
"WHERE doctor.id_doctor = appointment.id_doctor AND patient.id_patient = appointment.id_patient AND doctor.id_doctor = " +
id, connection);
}
else
{
appointmentDataAdapter = new MySqlDataAdapter(
"SELECT doctor.name_doctor, doctor.surname_doctor, doctor.speciality, appointment.datetime " +
"FROM doctor, appointment, patient " +
"WHERE patient.id_patient = appointment.id_patient AND doctor.id_doctor = appointment.id_doctor AND patient.id_patient = " +
id, connection);
}
new MySqlCommandBuilder(appointmentDataAdapter);
appointmentDataAdapter.Fill(dataSet, "Appointment");
dataGridView3.DataSource = getDataSet().Tables["Appointment"];
}
private void dataGridView1_CellClick(object sender,
DataGridViewCellEventArgs e)
{
int selectedRow = dataGridView1.SelectedCells[0].RowIndex;
int key = (int)dataGridView1.Rows[selectedRow].Cells[0].Value;
dataGridView2.ClearSelection();
FillDataGridView3ByAppointment("Doctor", key);
}
private void dataGridView2_CellClick(object sender,
DataGridViewCellEventArgs e)
{
int selectedRow = dataGridView2.SelectedCells[0].RowIndex;
int key = (int)dataGridView2.Rows[selectedRow].Cells[0].Value;
dataGridView1.ClearSelection();
FillDataGridView3ByAppointment("Patient", key);
}
}
}
I want to show data from data table on form_load using list box, and later update that data from list box on button click by Insert command. Function for that is fill_List(). This is my code:
OleDbConnection konekcija;
OleDbDataAdapter adapter = new OleDbDataAdapter();
DataTable dt = new DataTable();
public Form2()
{
InitializeComponent();
string putanja = Environment.CurrentDirectory;
string[] putanjaBaze = putanja.Split(new string[] { "bin" }, StringSplitOptions.None);
AppDomain.CurrentDomain.SetData("DataDirectory", putanjaBaze[0]);
konekcija = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=|DataDirectory|\B31Autoplac.accdb");
}
void fill_List()
{
konekcija.Open();
OleDbCommand komPrikaz = new OleDbCommand("SELECT * FROM GORIVO ORDER BY GorivoID ASC", konekcija);
adapter.SelectCommand = komPrikaz;
adapter.Fill(dt);
listBox1.Items.Clear();
for (int i = 0; i < dt.Rows.Count; i++)
{
string pom;
pom = dt.Rows[i][0].ToString() + " " + dt.Rows[i][1].ToString() + " " + dt.Rows[i][2];
listBox1.Items.Add(pom);
}
konekcija.Close();
}
private void Form2_Load(object sender, EventArgs e)
{
fill_List();
}
private void btnUpisi_Click(object sender, EventArgs e)
{
string s1, s2, s3;
s1 = tbSifra.Text;
s2 = tbNaziv.Text;
s3 = tbOpis.Text;
string Upisi = "INSERT INTO GORIVO (GorivoID, Naziv, Opis) VALUES (#GorivoID, #Naziv, #Opis)";
OleDbCommand komUpisi = new OleDbCommand(Upisi, konekcija);
komUpisi.Parameters.AddWithValue("#GorivoID", s1);
komUpisi.Parameters.AddWithValue("#Naziv", s2);
komUpisi.Parameters.AddWithValue("#Opis", s3);
string Provera = "SELECT COUNT (*) FROM GORIVO WHERE GorivoID=#GorivoID";
OleDbCommand komProvera = new OleDbCommand(Provera, konekcija);
komProvera.Parameters.AddWithValue("#GorivoID", s1);
try
{
konekcija.Open();
int br = (int)komProvera.ExecuteScalar();
if(br==0)
{
komUpisi.ExecuteNonQuery();
MessageBox.Show("Podaci su uspesno upisani u tabelu i bazu.", "Obavestenje");
tbSifra.Text = tbNaziv.Text = tbOpis.Text = "";
}
else
{
MessageBox.Show("U bazi postoji podatak sa ID = " + tbSifra.Text + ".", "Obavestenje");
}
}
catch (Exception ex1)
{
MessageBox.Show("Greska prilikom upisa podataka. " + ex1.ToString(), "Obavestenje");
}
finally
{
konekcija.Close();
fill_List();
}
}
Instead of this
It shows me this (added duplicates with new data)
Is there a problem in my function or somewhere else?
Another bug caused by global variables.
You are keeping a global variable for the DataTable filled by the fill_list method. This datatable is never reset to empty when you call fill_list, so at every call you add another set of rows to the datatable and then transfer this data inside the listbox. Use a local variable.
But the same rule should be applied also to the OleDbConnection and OleDbCommand. There is no need to keep global instances of them. Creating an object is really fast and the convenience to avoid global variables is better than the little nuisance to create an instance of the connection or the command.
void fill_List()
{
using(OleDbConnection konekcija = new OleDbConnection(......))
using(OleDbCommand komPrikaz = new OleDbCommand("SELECT * FROM GORIVO ORDER BY GorivoID ASC", konekcija))
{
DataTable dt = new DataTable();
konekcija.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(komPrikaz);
adapter.Fill(dt);
listBox1.Items.Clear();
for (int i = 0; i < dt.Rows.Count; i++)
{
string pom;
pom = dt.Rows[i][0].ToString() + " " + dt.Rows[i][1].ToString() + " " + dt.Rows[i][2];
listBox1.Items.Add(pom);
}
}
}
Clear your DataTable before filling it again.
void fill_List()
{
konekcija.Open();
OleDbCommand komPrikaz = new OleDbCommand("SELECT * FROM GORIVO ORDER BY GorivoID ASC", konekcija);
adapter.SelectCommand = komPrikaz;
dt.Clear(); // clear here
adapter.Fill(dt);
listBox1.Items.Clear();
for (int i = 0; i < dt.Rows.Count; i++)
{
string pom;
pom = dt.Rows[i][0].ToString() + " " + dt.Rows[i][1].ToString() + " " + dt.Rows[i][2];
listBox1.Items.Add(pom);
}
konekcija.Close();
}
Creating a project for school, I have a form with some user controls.
3 textboxes a checkbox and 2 buttons for navigating through the records.
When I change the text on one of the textboxes, the data will only reflect to the database when I click the "Next" or "Prev" button.
public partial class Navigeren : UserControl
{
private readonly SqLiteDataAccess _sqLiteDataAccess;
private Timer _saveTimer;
private DataViewManager _dsView;
public Navigeren()
{
InitializeComponent();
_sqLiteDataAccess = new SqLiteDataAccess();
DataBinding();
_saveTimer = new Timer {Interval = 1000};
_saveTimer.Tick += _saveTimer_Tick;
_saveTimer.Start();
}
private void _saveTimer_Tick(object sender, EventArgs e)
{
_sqLiteDataAccess.UpdatePersonen(_dsView.DataSet);
// Tried using SqLiteDataAccess.PersonenDataSet gives me the same result.
}
private void DataBinding()
{
_dsView = SqLiteDataAccess.PersonenDataSet.DefaultViewManager;
textId.DataBindings.Add("Text", _dsView, "Personen.id", false, DataSourceUpdateMode.OnPropertyChanged);
textNaam.DataBindings.Add("Text", _dsView, "Personen.name", false, DataSourceUpdateMode.OnPropertyChanged);
textAdres.DataBindings.Add("Text", _dsView, "Personen.adres", false, DataSourceUpdateMode.OnPropertyChanged);
checkGehuwd.DataBindings.Add("Checked", _dsView, "Personen.gehuwd", false, DataSourceUpdateMode.OnPropertyChanged);
}
private void buttonNext_Click(object sender, EventArgs e)
{
CurrencyManager cm = (CurrencyManager)this.BindingContext[_dsView, "Personen"];
if (cm.Position < cm.Count - 1)
{
cm.Position++;
}
}
private void buttonPrev_Click(object sender, EventArgs e)
{
if (this.BindingContext[_dsView, "Personen"].Position > 0)
{
this.BindingContext[_dsView, "Personen"].Position--;
}
}
}
Sorry for my english.
Greetings Andy
EDIT:
SQLiteDataAccess:
class SqLiteDataAccess
{
private SQLiteConnection _sqliteconnection;
private string _database = #"Database.sqlite";
private static DataSet _personenDataSet;
public static DataSet PersonenDataSet
{
get { return _personenDataSet; }
set { _personenDataSet = value; }
}
public SqLiteDataAccess()
{
OpenConnection();
CreateTable();
CreateTableGeslachten();
CreateTableLanden();
FillDataSet();
}
private void OpenConnection()
{
if (!File.Exists(_database))
SQLiteConnection.CreateFile(_database);
_sqliteconnection = new SQLiteConnection("Data Source=" + _database + ";Version=3;");
_sqliteconnection.Open();
}
private void CreateTable()
{
try
{
string sql = "CREATE TABLE Personen (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"name VARCHAR, " +
"adres VARCHAR, " +
"gehuwd INT, " +
"land INT, " +
"geslacht INT, " +
"telnr VARCHAR, " +
"studies VARCHAR, " +
"geboorteDatum DATETIME, " +
"foto BLOB)";
SQLiteCommand command = new SQLiteCommand(sql, _sqliteconnection);
command.ExecuteNonQuery();
}
catch (SQLiteException sle)
{
}
}
private void CreateTableGeslachten()
{
try
{
string sql = "CREATE TABLE Geslachten (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"geslacht TEXT," +
"FOREIGN KEY(id) REFERENCES Personen(geslacht));";
SQLiteCommand command = new SQLiteCommand(sql, _sqliteconnection);
command.ExecuteNonQuery();
InsertTableGeslachten();
}
catch (SQLiteException sle)
{
}
}
private void InsertTableGeslachten()
{
string sql = "INSERT INTO Geslachten(geslacht) VALUES('Man'), ('Vrouw');";
SQLiteCommand command = new SQLiteCommand(sql, _sqliteconnection);
command.ExecuteNonQuery();
}
private void CreateTableLanden()
{
try
{
string sql = "CREATE TABLE Landen (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"land TEXT," +
"FOREIGN KEY(id) REFERENCES Personen(land));";
SQLiteCommand command = new SQLiteCommand(sql, _sqliteconnection);
command.ExecuteNonQuery();
InsertTableLanden();
}
catch (SQLiteException sle)
{
}
}
public void Insert(string name, string adres, bool gehuwd, int land, int geslacht, string telnr, string studies,
string geboorteDatum, byte[] foto)
{
var sql =
new StringBuilder(
"insert into Personen (name, adres, gehuwd, land, geslacht, telnr, studies, geboorteDatum) values ('");
sql.Append(name).Append("','")
.Append(adres).Append("','")
.Append(Convert.ToInt32(gehuwd)).Append("','")
.Append(land).Append("','")
.Append(geslacht).Append("','")
.Append(telnr).Append("','")
.Append(studies).Append("','")
.Append(geboorteDatum).Append("');");
// .Append(foto).Append(");");
SQLiteCommand command = new SQLiteCommand(sql.ToString(), _sqliteconnection);
command.ExecuteNonQuery();
}
public void FillDataSet()
{
SqLiteDataAccess.PersonenDataSet = new DataSet();
try
{
string query = "select * from Personen";
SQLiteDataAdapter da = new SQLiteDataAdapter(query, _sqliteconnection);
da.Fill(PersonenDataSet, "Personen");
string query2 = "select id, geslacht from geslachten";
SQLiteDataAdapter da2 = new SQLiteDataAdapter(query2, _sqliteconnection);
da2.Fill(PersonenDataSet, "Geslachten");
string query3 = "select id, land from Landen";
SQLiteDataAdapter da3 = new SQLiteDataAdapter(query3, _sqliteconnection);
da3.Fill(PersonenDataSet, "Landen");
}
catch (Exception ex)
{
}
}
public void UpdatePersonen(DataSet ds)
{
try
{
string query = "select * from Personen";
SQLiteDataAdapter da = new SQLiteDataAdapter(query, _sqliteconnection);
SQLiteCommandBuilder sqLiteCommandBuilder = new SQLiteCommandBuilder(da);
da.Update(ds, "Personen");
}
catch (Exception ex)
{
MessageBox.Show("Test");
}
}
You don't need to change the position, you just need to call EndCurrentEdit method of the BindingManagerBase before save:
this.BindingContext[datasource, "datamember"].EndCurrentEdit();
Some Notes
Use BindingSource.
I recommend using a BindingSource component as data source which you want to use for data-binding. Then set the DataSource and DataMember of the BindingSource to the values which you want:
It enables you to perform data-binding at design time.
It enables you to use its methods and properties to navigation, add, remove and so on.
You can use it's sorting and filtering properties.
Use BindingNavigator.
Also use BindingNavigator control as a navigation toolbar. It's enough to set its BindingSource property to the BindingSource component which you used for data-binding, then its navigation button will do the job of navigation for you.
Also take a look at:
Why do I need to change the Binding Source Position before I can SaveChanges
Describes why changing position also does the trick.
Equivalent of MoveNext in VB.NET
Shows you how to create a rapid data application using designer features, data-binding, BindingSource and BindingNavigator using drag and drop. Also it share some useful links about these features.
i am trying to insert new row in Emp table in c# (disconnected mode), the new row successfully inserted but the dataset not updated, so when i search for the new row, i don't find it, but when i search for an old row, i find it.
the insertBTN button used to insert new row
the searchByID button used to search for row by its ID
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private SqlConnection conn;
private SqlDataAdapter adapter;
private DataSet ds;
private void Form1_Load(object sender, EventArgs e)
{
conn = new SqlConnection(#"data source=(local);initial catalog =Test;integrated security = true");
conn.Open();
adapter = new SqlDataAdapter("select * from Emp",conn);
ds = new DataSet();
adapter.Fill(ds,"Emp");
}
private void insertBTN_Click(object sender, EventArgs e)
{
try
{
int id = int.Parse(textBox1.Text);
string name = textBox2.Text;
string address = textBox3.Text;
int age = int.Parse(textBox4.Text);
int salary = int.Parse(textBox5.Text);
SqlCommand command = new SqlCommand("Insert into Emp values(" + id + ",'" + name + "','" + address + "'," + age + "," + salary + ")", conn);
command.ExecuteNonQuery();
adapter.Update(ds,"Emp");
MessageBox.Show("Employee added successfully");
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}
private void searchByID_Click(object sender, EventArgs e)
{
try
{
int id = int.Parse(textBox1.Text);
foreach (DataRow row in ds.Tables["Emp"].Rows)
{
if (Convert.ToInt32(row["id"]) == id)
{
textBox2.Text = Convert.ToString(row["name"]);
textBox3.Text = Convert.ToString(row["address"]);
textBox4.Text = Convert.ToString(row["age"]);
textBox5.Text = Convert.ToString(row["salary"]);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
The Update method of the DataAdapter doesn't read again but tries to execute the INSERT, DELETE and UPDATE commands derived from the original SELECT statement against the Rows in the DataTable that have their RowState changed
So, if you want to use the Update method of the adapter you could write
private void insertBTN_Click(object sender, EventArgs e)
{
try
{
DataRow row = ds.Tables["emp"].NewRow();
row.SetField<int>("id", int.Parse(textBox1.Text));
row.SetField<string>("name", textBox2.Text));
row.SetField<string>("address", textBox3.Text));
row.SetField<int>("age", int.Parse(textBox4.Text));
row.SetField<int>("salary", int.Parse(textBox5.Text));
ds.Tables["emp"].Rows.Add(row);
adapter.Update(ds,"Emp");
MessageBox.Show("Employee added successfully");
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}
At this point your DataSet contains the added row because you have added it manually and then passed everything to the Update method to write it to the database.
However, keep in mind that the Update method to work requires certain conditions to be present. You could read them in the DbDataAdapter.Update page on MSDN.
Mainly you need to have retrieved the primary key of the table, do not have more than one table joined together and you have used the DbCommandBuilder object to create the required commands (Again the example in the MSDN page explain it)
Not related to your question, but you could change your search method and avoid writing a loop to search for the ID
private void searchByID_Click(object sender, EventArgs e)
{
try
{
int id = int.Parse(textBox1.Text);
DataRow[] foundList = ds.Tables["Emp"].Select("Id = " + id);
if(foundList.Length > 0)
{
textBox2.Text = foundList[0].Field<string>("name");
textBox3.Text = foundList[0].Field<string>("address");
textBox4.Text = foundList[0].Field<int>("age").ToString();
textBox5.Text = foundList[0].Field<int>("salary").ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I have a form with a datagrid, which is populated wih data from a sqlserver database. The datagrid populates fine but I am having trouble posting back the changes made by the user, to the table in the sql database. My forms code is as follows:
public partial class frmTimesheet : Form
{
private DataTable tableTS = new DataTable();
private SqlDataAdapter adapter = new SqlDataAdapter();
private int currentTSID = 0;
public frmTimesheet()
{
InitializeComponent();
}
private void frmTimesheet_Load(object sender, EventArgs e)
{
string strUser = cUser.currentUser;
cMyDate cD = new cMyDate(DateTime.Now.ToString());
DateTime date = cD.GetDate();
txtDate.Text = date.ToString();
cboTSUser.DataSource = cUser.GetListOfUsers("active");
cboTSUser.DisplayMember = "UserID";
cboTSUser.Text = strUser;
CheckForTimeSheet();
PopulateTimeSheet();
}
private void CheckForTimeSheet()
{
string strUser = cboTSUser.Text;
cMyDate cD = new cMyDate(txtDate.Text);
DateTime date = cD.GetDate();
int newTSID = cTimesheet.TimeSheetExists(strUser, date);
if (newTSID != this.currentTSID)
{
tableTS.Clear();
if (newTSID == 0)
{
MessageBox.Show("Create TimeSheet");
}
else
{
this.currentTSID = newTSID;
}
}
}
private void PopulateTimeSheet()
{
try
{
string sqlText = "SELECT EntryID, CaseNo, ChargeCode, StartTime, FinishTime, Units " +
"FROM tblTimesheetEntries " +
"WHERE TSID = " + this.currentTSID + ";";
SqlConnection linkToDB = new SqlConnection(cConnectionString.BuildConnectionString());
SqlCommand sqlCom = new SqlCommand(sqlText, linkToDB);
SqlDataAdapter adapter = new SqlDataAdapter(sqlCom);
adapter.SelectCommand = sqlCom;
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.Fill(tableTS);
dataTimesheet.DataSource = tableTS;
}
catch (Exception eX)
{
string eM = "Error Populating Timesheet";
cError err = new cError(eX, eM);
MessageBox.Show(eM + Environment.NewLine + eX.Message);
}
}
private void txtDate_Leave(object sender, EventArgs e)
{
CheckForTimeSheet();
PopulateTimeSheet();
}
private void cboTSUser_DropDownClosed(object sender, EventArgs e)
{
CheckForTimeSheet();
PopulateTimeSheet();
}
private void dataTimesheet_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
try
{
adapter.Update(tableTS);
}
catch (Exception eX)
{
string eM = "Error on frmTimesheet, dataTimesheet_CellValueChanged";
cError err = new cError(eX, eM);
MessageBox.Show(eM + Environment.NewLine + eX.Message);
}
}
}
No exception occurs, and when I step through the issue seems to be with the SqlCommandBuilder which does NOT build the INSERT / UPDATE / DELETE commands based on my gien SELECT command.
Can anyone see what I am doing wrong?
What am I missing?
You need to set the UpdateCommand instead of SelectCommand on update:
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommandBuilder sqlBld = new SqlCommandBuilder(adapter)
adapter.UpdateCommand = sqlBld.GetUpdateCommand() ;
The question is old, but the provided answer by#Anurag Ranjhan need to be corrected.
You need not to write the line:
adapter.UpdateCommand = sqlBld.GetUpdateCommand() ;
and enough to write:
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommandBuilder sqlBld = new SqlCommandBuilder(adapter)
//remove the next line
//adapter.UpdateCommand = sqlBld.GetUpdateCommand() ;
The Sql update/insert/delete commands are auto generated based on this line
SqlCommandBuilder sqlBld = new SqlCommandBuilder(adapter)
You can find the generated update sql by executing the line:
sqlBld.GetUpdateCommand().CommandText;
See the example How To Update a SQL Server Database by Using the SqlDataAdapter Object in Visual C# .NET
The problem said by OP can be checked by reviewing the Sql Statement sent by the client in SQl Server Profiler.