SqlDataAdapter.Update or SqlCommandBuilder not working - c#

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.

Related

DataSet not updated with new row inserted in 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);
}

Not getting any row data from database using c# asp.net.

I can not get any row data from database using c# asp.net.I am trying to fetch one row data from my DB but it is not returning any row.I am using 3-tire architecture for this and i am explaining my code below.
index.aspx.cs:
protected void userLogin_Click(object sender, EventArgs e)
{
if (loginemail.Text.Trim().Length > 0 && loginpass.Text.Trim().Length >= 6)
{
objUserBO.email_id = loginemail.Text.Trim();
objUserBO.password = loginpass.Text.Trim();
DataTable dt= objUserBL.getUserDetails(objUserBO);
Response.Write(dt.Rows.Count);
}
}
userBL.cs:
public DataTable getUserDetails(userBO objUserBO)
{
userDL objUserDL = new userDL();
try
{
DataTable dt = objUserDL.getUserDetails(objUserBO);
return dt;
}
catch (Exception e)
{
throw e;
}
}
userDL.cs:
public DataTable getUserDetails(userBO objUserBO)
{
SqlConnection con = new SqlConnection(CmVar.convar);
try
{
con.Open();
DataTable dt = new DataTable();
string sql = "SELECT * from T_User_Master WHERE User_Email_ID= ' " + objUserBO.email_id + "'";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter objadp = new SqlDataAdapter(cmd);
objadp.Fill(dt);
con.Close();
return dt;
}
catch(Exception e)
{
throw e;
}
}
When i am checking the output of Response.Write(dt.Rows.Count);,it is showing 0.So please help me to resolve this issue.
It looks like your your query string has a redundant space between ' and " mark. That might be causing all the trouble as your email gets space in front.
It is by all means better to add parameters to your query with use of SqlConnection.Parameters property.
string sql = "SELECT * from T_User_Master WHERE User_Email_ID=#userID";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#userID", SqlDbType.NVarChar);
cmd.Parameters["#userID"].Value = objUserBO.email_id;

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

What is the connection string if my database is host online, not in my local computer? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can WCF consuming data from database phpmyadmin?
I want to ask about the connection string that should i write at WCF. My database is host at phpmyadmin.
How should I write the connections string? if the database is using microsoft access or sqlserver that run at my computer, I done it already. Now, I'm curious if my database at phpmyadmin.
Honestly, I already asked this question in this forum yesterday. I say a big thanks to whom answer my question but I dont think that is a answer. I'm sorry for being stupid and don't understand what you said yesterday. If you get mad, you don't need to answer. thanks.
Out of the topic, this my WCF code.
public class Jobs : IJobs
{
SqlConnection conn = new SqlConnection("Data Source=127.0.0.1; Initial Catalog=mydatabase;User=ael;Password=123456;Integrated Security=False");
SqlDataAdapter da;
DataSet ds;
Data data = new Data();
List<Data> listdata = new List<Data>();
public DataSet Details()
{
conn.Open();
ds = new DataSet();
da = new SqlDataAdapter("Select * from data", conn);
da.Fill(ds);
conn.Close();
return ds;
}
public Data GetDetails(int jobid)
{
conn.Open();
ds = new DataSet();
da = new SqlDataAdapter("Select * from data where id = " + jobid, conn);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
data.userid = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
data.firstname = ds.Tables[0].Rows[0][1].ToString();
data.lastname = ds.Tables[0].Rows[0][2].ToString();
data.location = ds.Tables[0].Rows[0][3].ToString();
ds.Dispose();
}
conn.Close();
return data;
}
public List<Data> GetAllDetails()
{
conn.Open();
ds = new DataSet();
da = new SqlDataAdapter("Select * from data", conn);
da.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows)
{
listdata.Add(
new Data
{
userid = Convert.ToInt32(dr[0]),
firstname = dr[1].ToString(),
lastname = dr[2].ToString(),
location = dr[3].ToString()
}
);
}
conn.Close();
return listdata;
}
}
this is the wpf
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
if (textbox1.Text.Trim().Length != 0)
{
ServiceReference1.JobsClient jc = new ServiceReference1.JobsClient();
var x = jc.GetDetails(Convert.ToInt32(textbox1.Text));
if (x.userid != 0)
{
textbox2.Text = x.userid.ToString();
textbox3.Text = x.firstname;
textbox4.Text = x.lastname;
textbox5.Text = x.location;
}
else
MessageBox.Show("RecordNotFound ... !", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
MessageBox.Show("EnterID", "Message", MessageBoxButton.OK, MessageBoxImage.Warning);
}
private void button2_Click(object sender, RoutedEventArgs e)
{
ServiceReference1.JobsClient jc = new ServiceReference1.JobsClient();
dataGrid1.ItemsSource = jc.Details().Tables[0].DefaultView;
}
private void button3_Click(object sender, RoutedEventArgs e)
{
ServiceReference1.JobsClient jc = new ServiceReference1.JobsClient();
dataGrid1.ItemsSource = jc.GetAllDetails() ;
}
}
I already create a user at phpmyadmin, and use it at my WCF. but whenever I run, its show "login failed for user ael".
Is there something I need to change in the connection string?
thanks before.
If I understand correctly you need an example for the connection string.
So for the connection string format please see ConnectionsStrings.com
For example, if you are using the standard port and did not change it:
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
Then you can to use the MySQL Connector (Namespace MySql.Data.MySqlClient downloadable here) and connect to the MySQL database programatically as explained in detail in this tutorial: Connection to the MySQL Server.

Gridview Update error

I am doing a small application in ASP.net(C#) with MS Access. I have a Gridview where I have a "Update" command. During run time I had put break point in RowUpdating() method. Everything works on well with no errors, the parameters are getting updated in the code behind. But in the output, gridview is not updating and also not in DB.
HERE IS THE CODE:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string ID = GridView1.Rows[e.RowIndex].Cells[1].Text;
string CName= ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
string AName = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
string APhone = ((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text;
string AEmail = ((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text;
string Note = ((TextBox)GridView1.Rows[e.RowIndex].Cells[6].Controls[0]).Text;
UpdateRecord(ID, CName, AName, APhone, AEmail, Note); // GridView1.EditIndex = -1; BindGridView();
}
UpdateRecord() Method:
The update method works well, during the run with breakpoints all the parameters get the updated values but it is not shown in the gridview and not updated in DB
private void UpdateOrAddNewRecord(string ID, string CName, string AName, string APhone, string AEmail, string Note)
{
OleDbConnection connection = null;
string conStr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\arjun.giridhar\Desktop\db1.mdb;Persist Security Info=False";
string sqlStatement = "UPDATE Carriers" + " SET CarrierName = #CarrierName, AccountRepName = #AccountRepName, AccountRepContactPhone = #AccountRepContactPhone, AccountRepEmail= #AccountRepEmail, Notes=#Notes" + " WHERE CarrierID = #CarrierID";
try
{
connection = new OleDbConnection(conStr);
connection.Open();
OleDbCommand cmd = new OleDbCommand(sqlStatement, connection);
cmd.Parameters.AddWithValue("#CarrierID", ID);
cmd.Parameters.AddWithValue("#CarrierName", CName);
cmd.Parameters.AddWithValue("#AccountRepName", AName);
cmd.Parameters.AddWithValue("#AccountRepContactPhone", APhone);
cmd.Parameters.AddWithValue("#AccountRepEmail", AEmail);
cmd.Parameters.AddWithValue("#Notes", Note);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
string msg = "Update Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
}
BindGridView() Method:
private void BindGridView()
{
DataTable dt = new DataTable();
OleDbConnection connection = new OleDbConnection(conStr);
try
{
connection.Open();
string sqlStatement = "SELECT * FROM Carriers";
OleDbCommand cmd = new OleDbCommand(sqlStatement, connection);
OleDbDataAdapter sqlDa = new OleDbDataAdapter(cmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataSourceID = string.Empty;
GridView1.DataBind();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
}
Kindly give me a solution.
Regards,
Arjun
I found another article here: Gridview not updating value which said that this is caused by binding your grid in the Page_Load and not checking for postback. I changed my Page_load to:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGridView();
}
}
That worked.

Categories