DataSet not updated with new row inserted in C# - c#

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);
}

Related

How to update oracle database table in c# with variable from text.box

When I click on update button I dont get any errors but my table isnt updated.
private void Button3_Click(object sender, EventArgs e)
{
try
{
OracleConnection cnn = new OracleConnection(oradb);
cnn.Open();
oracleCommand = new OracleCommand("UPDATE KUPAC SET NAZIVKUPCA = :NAZIVKUPCA, PIB = :PIB, MATICNIBROJ = :MATICNIBROJ, ZIRORACUN = :ZIRORACUN, EMAIL = :EMAIL WHERE KUPACID = :KUPACID", cnn);
oracleCommand.Parameters.Add("#KUPACID", Convert.ToInt32(txtKupacId.Text));
oracleCommand.Parameters.Add("#NAZIVKUPCA", txtNazivKupca.Text);
oracleCommand.Parameters.Add("#PIB", txtPIB.Text);
oracleCommand.Parameters.Add("#MATICNIBROJ", txtJMBG.Text);
oracleCommand.Parameters.Add("#ZIRORACUN", txtZiroRacun.Text);
oracleCommand.Parameters.Add("#EMAIL", txtEmail.Text);
int result = oracleCommand.ExecuteNonQuery();
MessageBox.Show("Kupac uspesno izmenjen");
}
catch (Exception exc)
{
MessageBox.Show("Greska prilikom izmena u bazi." + exc.Message);
}
finally
{
}
OsveziKupce();
ObrisiPolja();
}
I get message "Kupac uspesno izmenjen", which means that table should be updated, but nothing happens

Deleting a row in a database from datagridview C#

I'm trying to remove an entry from both the datagridview and the database. I got it so it removes the row from the data grid view but it fails to delete it also from the database. Here is my code I have in place:
private void listBtn_Click(object sender, EventArgs e)
{
MySqlDataAdapter mysqldatadapter = new MySqlDataAdapter("select id, username from members ORDER BY id", new MySqlConnection(conn.connectionString));
mysqldatadapter.Fill(ds);
dataGridView.DataSource = ds.Tables[0];
listBtn.Enabled = false;
}
private void btnDelete_Click(object sender, EventArgs e)
{
using (MySqlConnection dbConn = new MySqlConnection(conn.connectionString))
{
dbConn.Open();
for (int i = 0; i < dataGridView.Rows.Count; i++)
{
DataGridViewRow row = dataGridView.Rows[i];
if (row.Selected == true)
{
dataGridView.Rows.RemoveAt(i);
MySqlCommand cmd = dbConn.CreateCommand();
cmd.CommandText = "DELETE FROM members WHERE id = " + i;
try
{
cmd.ExecuteNonQuery();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
}
dbConn.Close();
}
}
I'm at a loss concerning this, any help would be appreciated.
Thanks!
Update - Is there a way to grab the value of individual cells to pass to the mysql command? For instance, grabbing the id?
Your values for i probably don't match the id fields in the member table.
You probably need to change this line:
cmd.CommandText = "DELETE FROM members WHERE id = " + i;
to
cmd.CommandText = "DELETE FROM members WHERE id = " + row.cells[id.Index].ToString();

How to insert data into two SQL Server tables in asp.net

I have two tables, the first table is Course and this table contains three columns Course_ID, Name_of_course, DeptID; and the second table is Department and it has three columns DeptID, DepName, College.
I put a GridView to display the data that I will add it. But when I write the command to insert the data in both tables the data don't add. I used this command
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
GridViewRow r = GridView1.SelectedRow;
Dbclass db = new Dbclass();
string s = "";
DataTable dt = db.getTable(s);
ddcollege.SelectedValue = dt.Rows[0]["College"].ToString();
dddept.SelectedValue = dt.Rows[1]["DepName"].ToString();
tbid.Text = r.Cells[0].Text;
tbcourse_name.Text = r.Cells[1].Text;
lblid.Text = tbid.Text;
lberr.Text = "";
}
catch (Exception ex)
{
lberr.Text = ex.Message;
}
}
protected void btadd_Click(object sender, EventArgs e)
{
try
{
if (tbid.Text == "")
{
lberr.Text = "Please input course id";
return;
}
if (tbcourse_name.Text == "")
{
lberr.Text = "Please input course name";
return;
}
string s = "Insert into Course(Course_ID,Name_of_course) values ('" + tbid.Text + "','" + tbcourse_name.Text + "')";
s = "INSERT INTO Department (DepName,College,DeptID) VALUES ('"+dddept.SelectedValue+"','"+ddcollege.SelectedValue+"','"+tbdeptID.Text+"')";
Dbclass db = new Dbclass();
if (db.Run(s))
{
lberr.Text = "The data is added";
lblid.Text = tbid.Text;
}
else
{
lberr.Text = "The data is not added";
}
SqlDataSource1.DataBind();
GridView1.DataBind();
}
catch (Exception ex)
{
lberr.Text = ex.Message;
}
}
Here is the Dbclass code:
public class Dbclass
{
SqlConnection dbconn = new SqlConnection();
public Dbclass()
{
try
{
dbconn.ConnectionString = #"Data Source=Fingerprint.mssql.somee.com;Initial Catalog=fingerprint;Persist Security Info=True;User ID=Fingerprint_SQLLogin_1;Password=********";
dbconn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
//----- run insert, delete and update
public bool Run(String sql)
{
bool done= false;
try
{
SqlCommand cmd = new SqlCommand(sql,dbconn);
cmd.ExecuteNonQuery();
done= true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return done;
}
//----- run insert, delete and update
public DataTable getTable(String sql)
{
DataTable done = null;
try
{
SqlDataAdapter da = new SqlDataAdapter(sql, dbconn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds.Tables[0];
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return done;
}
}
Thank you all
The main thing I can see is you are assigning two different things to your "s" variable.
At this point db.Run(s) the value is "Insert into Department etc" and you have lost the first sql string you assigned to "s"
Try:
string s = "Insert into Course(Course_ID,Name_of_course) values ('" + tbid.Text + "','" + tbcourse_name.Text + "')";
s += "INSERT INTO Department (DepName,College,DeptID) VALUES ('"+dddept.SelectedValue+"','"+ddcollege.SelectedValue+"','"+tbdeptID.Text+"')";
Notice the concatenation(+=). Otherwise as mentioned above using a stored procedure or entity framework would be a better approach. Also try to give your variables meaningful names. Instead of "s" use "insertIntoCourse" or something that describes what you are doing
When a value is inserted into a table(Table1) and and value has to be entered to into another table(Table2) on insertion of value to Table1, you can use triggers.
https://msdn.microsoft.com/en-IN/library/ms189799.aspx
"tbdeptID.Text" is giving you the department Id only right? You should be able to modify your first statement
string s = "Insert into Course(Course_ID,Name_of_course,) values ('" + tbid.Text + "','" + tbcourse_name.Text + "',)";
Please start running SQL Profiler, it is a good tool to see what is the actual query getting executed in server!

Dataset showing unexpected Data

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

SqlDataAdapter.Update or SqlCommandBuilder not working

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.

Categories