As the title indicates, I'm having trouble updating a datagrid in WPF. Basically what I'm trying to accomplish is a datagrid, that is connected to a SQL Server database, that updates automatically once a user enters information into a few textboxes and clicks a submit button. You'll notice that I have a command that joins two tables. The data from the Quote_Data table will be inserted by a different user at a later time. For now my only concern is getting the information from the textboxes and into the General_Info table, and from there into my datagrid. The code, which I'll include below compiles fine, but when I hit the submit button, nothing happens. This is the first application I've ever built working with a SQL Database so many of these concepts are new to me, which is why you'll probably look at my code and wonder what is he thinking.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public DataSet mds; // main data set (mds)
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
try
{
string connectionString = Sqtm.Properties.Settings.Default.SqtmDbConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
//Merging tables General_Info and Quote_Data
SqlCommand cmd = new SqlCommand("SELECT General_Info.Quote_ID, General_Info.Open_Quote, General_Info.Customer_Name,"
+ "General_Info.OEM_Name, General_Info.Qty, General_Info.Quote_Num, General_Info.Fab_Drawing_Num, "
+ "General_Info.Rfq_Num, General_Info.Rev_Num, Quote_Data.MOA, Quote_Data.MOQ, "
+ "Quote_Data.Markup, Quote_Data.FOB, Quote_Data.Shipping_Method, Quote_Data.Freight, "
+ "Quote_Data.Vendor_Price, Unit_Price, Quote_Data.Difference, Quote_Data.Vendor_NRE_ET, "
+ "Quote_Data.NRE, Quote_Data.ET, Quote_Data.STI_NET, Quote_Data.Mfg_Time, Quote_Data.Delivery_Time, "
+ "Quote_Data.Mfg_Name, Quote_Data.Mfg_Location "
+ "FROM General_Info INNER JOIN dbo.Quote_Data ON General_Info.Quote_ID = Quote_Data.Quote_ID",
connection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
MainGrid.ItemsSource = dt.DefaultView;
mds = new DataSet();
da.Fill(mds, "General_Info");
MainGrid.DataContext = mds.Tables["General_Info"];
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
// renaming column names from the database so they are easier to read in the datagrid
MainGrid.Columns[0].Header = "#";
MainGrid.Columns[1].Header = "Date";
MainGrid.Columns[2].Header = "Customer";
MainGrid.Columns[3].Header = "OEM";
MainGrid.Columns[4].Header = "Qty";
MainGrid.Columns[5].Header = "Quote Number";
MainGrid.Columns[6].Header = "Fab Drawing Num";
MainGrid.Columns[7].Header = "RFQ Number";
MainGrid.Columns[8].Header = "Rev Number";
MainGrid.Columns[9].Header = "MOA";
MainGrid.Columns[10].Header = "MOQ";
MainGrid.Columns[11].Header = "Markup";
MainGrid.Columns[12].Header = "FOB";
MainGrid.Columns[13].Header = "Shipping";
MainGrid.Columns[14].Header = "Freight";
MainGrid.Columns[15].Header = "Vendor Price";
MainGrid.Columns[16].Header = "Unit Price";
MainGrid.Columns[17].Header = "Difference";
MainGrid.Columns[18].Header = "Vendor NRE/ET";
MainGrid.Columns[19].Header = "NRE";
MainGrid.Columns[20].Header = "ET";
MainGrid.Columns[21].Header = "STINET";
MainGrid.Columns[22].Header = "Mfg. Time";
MainGrid.Columns[23].Header = "Delivery Time";
MainGrid.Columns[24].Header = "Manufacturer";
MainGrid.Columns[25].Header = "Mfg. Location";
}
private void submitQuotebtn_Click(object sender, RoutedEventArgs e)
{
CustomerData newQuote = new CustomerData();
int quantity;
quantity = Convert.ToInt32(quantityTxt.Text);
string theDate = System.DateTime.Today.Date.ToString("d");
newQuote.OpenQuote = theDate;
newQuote.CustomerName = customerNameTxt.Text;
newQuote.OEMName = oemNameTxt.Text;
newQuote.Qty = quantity;
newQuote.QuoteNumber = quoteNumberTxt.Text;
newQuote.FdNumber = fabDrawingNumberTxt.Text;
newQuote.RfqNumber = rfqNumberTxt.Text;
newQuote.RevNumber = revNumberTxt.Text;
try
{
string insertConString = Sqtm.Properties.Settings.Default.SqtmDbConnectionString;
using (SqlConnection insertConnection = new SqlConnection(insertConString))
{
insertConnection.Open();
SqlDataAdapter adapter = new SqlDataAdapter(Sqtm.Properties.Settings.Default.SqtmDbConnectionString, insertConnection);
SqlCommand updateCmd = new SqlCommand("UPDATE General_Info " + "Quote_ID = #Quote_ID, "
+ "Open_Quote = #Open_Quote, " + "OEM_Name = #OEM_Name, " + "Qty = #Qty, "
+ "Quote_Num = #Quote_Num, " + "Fab_Drawing_Num = #Fab_Drawing_Num, "
+ "Rfq_Num = #Rfq_Num, " + "Rev_Num = #Rev_Num "
+ "WHERE Quote_ID = #Quote_ID");
updateCmd.Connection = insertConnection;
System.Data.SqlClient.SqlParameterCollection param = updateCmd.Parameters;
//
// Add new SqlParameters to the command.
//
param.AddWithValue("Open_Quote", newQuote.OpenQuote);
param.AddWithValue("Customer_Name", newQuote.CustomerName);
param.AddWithValue("OEM_Name", newQuote.OEMName);
param.AddWithValue("Qty", newQuote.Qty);
param.AddWithValue("Quote_Num", newQuote.QuoteNumber);
param.AddWithValue("Fab_Drawing_Num", newQuote.FdNumber);
param.AddWithValue("Rfq_Num", newQuote.RfqNumber);
param.AddWithValue("Rev_Num", newQuote.RevNumber);
adapter.UpdateCommand = updateCmd;
adapter.Update(mds.Tables[0]);
mds.AcceptChanges();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Thanks in advance to anyone who can help, I really appreciate it,
Andrew
You are not setting the Quote_ID parameter. So your update it likely running WHERE Quote_ID = null so nothing updates.
using LINQ I was able to resolve the issue. Here's the code:
var sqtmDC = new SqtmLinqDataContext();
var mainTable = from generalInfo in sqtmDC.GetTable<General_Info>()
//join quoteData in sqtmDataContext.GetTable<Quote_Data>() on generalInfo.Quote_ID equals quoteData.Quote_ID
select generalInfo;
myGrid.ItemsSource = mainTable;
}
private void submitBtn_Click(object sender, RoutedEventArgs e)
{
var sqtmDC = new SqtmLinqDataContext();
// string theDate = System.DateTime.Today.Date.ToString("d");
int quantity = Convert.ToInt32(quantityTxt.Text);
General_Info insert = new General_Info();
insert.Open_Quote = DateTime.UtcNow;
insert.Customer_Name = customerNameTxt.Text;
insert.OEM_Name = oemNameTxt.Text;
insert.Qty = quantity;
insert.Quote_Num = quoteNumberTxt.Text;
insert.Fab_Drawing_Num = fabDrawingNumTxt.Text;
insert.Rfq_Num = rfqNumberTxt.Text;
insert.Rev_Num = revNumberTxt.Text;
sqtmDC.General_Infos.InsertOnSubmit(insert);
sqtmDC.SubmitChanges();
int quoteID = insert.Quote_ID;
var mainTable = from generalInfo in sqtmDC.GetTable<General_Info>()
select generalInfo;
myGrid.ItemsSource = mainTable;
Are you trying to update an existing row or insert a new row?
Cause if you need to insert then the proper command is insert (not update).
To get the Identity value of the inserted row you use Scope_Identity().
And you can only insert into one table at a time.
Scope_Identity() is NOT a param
Do not try and use it as a param
See example below
INSERT INTO Sales.Customer ([TerritoryID],[PersonID]) VALUES (8,NULL);
GO
SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY];
There are lots of examples on MSDN.Microsoft.com
Related
I am trying to perform CRUD operation on winform
This is for ASP.NET winform in which whenever I try to insert, update or delete the data to or from the database first of all rows and inside content gets duplicated
https://imgur.com/a/d5jgv6H
however, upon restarting the application data shows up correctly
private void button2_Click(object sender, EventArgs e)
{
//insert
try
{
con.Open();
//.text property gets/Sets text associated with this control
String name = textBox1.Text.ToString();
String address = textBox2.Text.ToString();
String number = textBox3.Text.ToString();
long pnumber = Int64.Parse(number);
String sem = textBox4.Text.ToString();
long semester = Int64.Parse(sem);
string branch = comboBox1.SelectedItem.ToString();
String query = "insert into student values('" + name + "','" + address + "'," + pnumber + "," + semester + ",'" + branch + "')";
SqlCommand sqlcom = new SqlCommand(query, con);
int i = sqlcom.ExecuteNonQuery();
if (i >= 1)
{
MessageBox.Show("Student has been Registered: " + name);
}
else
{
MessageBox.Show("Registration Failed ! ");
}
//clearing data
button1_Click(sender, e);
show();
con.Close();
}
catch (Exception exp)
{
MessageBox.Show("Error is : " + exp.ToString());
}
}
void show()
{
String query = "select * from student";
SqlDataAdapter adapter = new SqlDataAdapter(query, con);
DataTable dataInTable = new DataTable();
adapter.Fill(dataInTable);
//DataRow represents row of data in DataTable
foreach (DataRow item in dataInTable.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = item[0].ToString();
dataGridView1.Rows[n].Cells[1].Value = item[1].ToString();
dataGridView1.Rows[n].Cells[2].Value = item[2].ToString();
dataGridView1.Rows[n].Cells[3].Value = item[3].ToString();
dataGridView1.Rows[n].Cells[4].Value = item[4].ToString();
}
}
The query works fine but rows still get duplicated. What's the problem?
I can't find any bug, so I assume I am doing something incorrectly.
Your show method adds rows to the grid, but it never removes the rows which are already in the grid.
Normally one would use data binding to populate a DataGridView or other data-bound controls. I'm going to assume you have reasons for just adding rows directly (perhaps it's simpler for your needs) and not change that. Given that structure, probably the easiest thing to do is just to clear the grid before adding the new rows:
void show()
{
String query = "select * from student";
SqlDataAdapter adapter = new SqlDataAdapter(query, con);
DataTable dataInTable = new DataTable();
adapter.Fill(dataInTable);
dataGridView1.Rows.Clear(); // <--- here
foreach (DataRow item in dataInTable.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = item[0].ToString();
dataGridView1.Rows[n].Cells[1].Value = item[1].ToString();
dataGridView1.Rows[n].Cells[2].Value = item[2].ToString();
dataGridView1.Rows[n].Cells[3].Value = item[3].ToString();
dataGridView1.Rows[n].Cells[4].Value = item[4].ToString();
}
}
That way any time you are about to populate the grid with new data, you first clear the existing data from it.
ComboBox doesn't show the data, I populate my combobox with data from my database this way:
private void PartDefective(string id)
{
cmd = new SQLiteCommand("Select * FROM Part_defective where testers = '" + id + "'", DBcon);
if (DBcon.State == ConnectionState.Closed)
DBcon.Open();
myDA = new SQLiteDataAdapter(cmd);
myDataSet = new DataSet();
myDA.Fill(myDataSet, "comboBox6");
this.comboBox6.DataSource = myDataSet.Tables["comboBox6"].DefaultView;
this.comboBox6.ValueMember = "Part";
this.comboBox6.DisplayMember = "Part";
this.comboBox6.SelectedItem = "ID";
this.comboBox6.SelectedIndex = -1;
DBcon.Close();
}
And to show the data from the database I used :
private void comboBox6_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.comboBox6.SelectedValue == null)
{
testerid = "1";
}
else
{
part = this.comboBox6.SelectedText.ToString();
}
}
There is absolutely no reason to define the SelectedItem or SelectedIndex.
The SelectedIndexChanged Event is also completely redundant for displaying your combobox.
Remove these lines and see if it solved your problem.
this.comboBox6.SelectedItem = "ID";
this.comboBox6.SelectedIndex = -1;
If the combobox is still empty, the root of problem has to be with the fetching of your data and filling the datasource.
Put a breakpoint on this line:
this.comboBox6.DataSource = myDataSet.Tables["comboBox6"].DefaultView;
And then look at the value of myDataSet.Tables["comboBox6"] in the watch or quickwatch window. Are there any rows?
Also change your code:
string sql = "Select * FROM Part_defective where testers = '" + id + "'";
cmd = new SQLiteCommand(sql, DBcon);
Put a breakpoint there, see what the value of sql is.
Manually run the sql against your database and see if there are any results.
We recently upgraded our solution to the new Managed ODP.Net (v4.121.2.0, from v4.121.1.0) and have come across a problem with udpating to CLOB fields when the field has between 1001 and 4000 characters. When you attempt to do that an error ORA-1461 is thrown from ODP.Net.
Run the same code and data, using the earlier version of ODP.Net and it works fine. Also, you can insert records with 1001 and 4000 characters, you just can't update them.
I've created a sample program in C# that demonstrates the problem. The program does the following:
It creates a 3 column table, one column a CLOB, in the database
It creates an in-memory .Net DataSet object to match.
Creates a new record in the DataSet with 1400 characters in the CLOB field.
Saves the DataSet to the database with an INSERT statement.
Updates the CLOB field in the DataSet with some new data, again 1400 characters worth of data.
Saves the DataSet to the database, and the ORA-1461 is thrown.
I don't have an Oracle Support account, so where do you report to Oracle problems with ODP.Net?
Sample C# code that demonstrates the problem:
using System;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using Oracle.ManagedDataAccess.Client;
class CLOBTest
{
string _TableName = "CLOBTEST";
string _ServerName = "servername";
string _UserName = "username";
string _Password = "password";
public void CLOBTest1()
{
// Create a physical data table, if needed, in the Oracle DB that has the CLOB column
CreateTable();
// Create a dataset for the CLOBTEST table, fill it with a new row
DataSet CLOBInfo = BuildCLOBTestDataSet();
DataTable CLOBTable = CLOBInfo.Tables[_TableName];
DataRow CLOBRow = CLOBTable.NewRow();
CLOBRow["ACTION_CODE"] = DateTime.Now.ToString("s");
CLOBRow["DESCRIPTION"] = "CLOB Slim Test";
// The size of text in the CLOB field is critical to reproducing this defect.
// It *only* happens when the field has between 1001 and 4000 characters.
int LOBFieldSize = 1400;
string CLOBText = DateTime.Now.ToString("s") + " " + new string('-', LOBFieldSize);
CLOBRow["SCRIPT_TEXT"] = CLOBText.Substring(0, LOBFieldSize);
CLOBTable.Rows.Add(CLOBRow);
// Add that row to the DB, and then mark the DS with AcceptChanges
InsertRow(CLOBInfo);
// Update that row with some new data.
CLOBText = DateTime.Now.ToString("s") + " :: " + CLOBText;
CLOBRow["SCRIPT_TEXT"] = CLOBText.Substring(0, LOBFieldSize);
// Error (ORA-1461) happens in the UPDATE when the CLOB has 1001 - 4000 characters in it.
UpdateRow(CLOBInfo);
}
private void CreateTable()
{
if (TableExists())
return;
using (OracleConnection oc = OpenConnection())
{
using (OracleCommand ocmd = oc.CreateCommand())
{
string SQL = "CREATE TABLE " + _TableName + " (ACTION_CODE VARCHAR2(30) NOT NULL, DESCRIPTION VARCHAR2(50) NOT NULL, SCRIPT_TEXT CLOB, CONSTRAINT CLOBTEST_PK PRIMARY KEY (ACTION_CODE))";
ocmd.CommandText = SQL;
ocmd.ExecuteNonQuery();
AddLogMessage("Table created.");
}
}
}
private bool TableExists()
{
using (OracleConnection oc = OpenConnection())
{
using (OracleCommand ocmd = oc.CreateCommand())
{
string SQL = "SELECT COUNT(*) FROM USER_TABLES WHERE TABLE_NAME = '" + _TableName + "'";
ocmd.CommandText = SQL;
object teRaw = ocmd.ExecuteScalar();
bool te = (bool)(int.Parse(teRaw.ToString()) > 0);
AddLogMessage("Table exists? " + te.ToString());
return te;
}
}
}
private void InsertRow(DataSet CLOBInfo)
{
string SQL = "INSERT INTO " + _TableName + " (ACTION_CODE, DESCRIPTION, SCRIPT_TEXT) VALUES (:pACTION_CODE, :pDESCRIPTION, :pSCRIPT_TEXT)";
using (OracleConnection oc = OpenConnection())
{
using (OracleDataAdapter oda = new OracleDataAdapter())
{
using (OracleCommand ocmd = oc.CreateCommand())
{
CreateDataParameters(ocmd);
ocmd.CommandText = SQL;
oda.InsertCommand = ocmd;
DataRow[] updRows = CLOBInfo.Tables[_TableName].Select(null, null, DataViewRowState.Added);
if (updRows.Length > 0)
{
int rc = oda.Update(updRows);
CLOBInfo.AcceptChanges();
AddLogMessage("Row inserted into CLOBTEST. rc = " + rc.ToString());
}
else
AddLogMessage("No rows to insert.");
}
}
}
}
private void UpdateRow(DataSet CLOBInfo)
{
string SQL = "UPDATE " + _TableName + " SET ACTION_CODE = :pACTION_CODE, DESCRIPTION = :pDESCRIPTION, SCRIPT_TEXT = :pSCRIPT_TEXT WHERE ACTION_CODE = :pOLDACTION_CODE";
using (OracleConnection oc = OpenConnection())
{
using (OracleDataAdapter oda = new OracleDataAdapter())
{
using (OracleCommand ocmd = oc.CreateCommand())
{
ocmd.CommandText = SQL;
CreateDataParameters(ocmd);
OracleParameter kp = new OracleParameter();
kp.ParameterName = "pOLDACTION_CODE";
kp.SourceColumn = "ACTION_CODE";
kp.SourceVersion = DataRowVersion.Original;
ocmd.Parameters.Add(kp);
oda.UpdateCommand = ocmd;
DataRow[] updRows = CLOBInfo.Tables[_TableName].Select(null, null, DataViewRowState.ModifiedCurrent);
if (updRows.Length > 0)
{
int rc = oda.Update(updRows);
CLOBInfo.AcceptChanges();
AddLogMessage("CLOBTEST row updated. rc = " + rc.ToString());
}
else
AddLogMessage("No rows to update.");
}
}
}
}
private void CreateDataParameters(OracleCommand ocmd)
{
OracleParameter pActionCode = new OracleParameter();
pActionCode.ParameterName = "pACTION_CODE";
pActionCode.SourceColumn = "ACTION_CODE";
ocmd.Parameters.Add(pActionCode);
OracleParameter pDescription = new OracleParameter();
pDescription.ParameterName = "pDESCRIPTION";
pDescription.SourceColumn = "DESCRIPTION";
ocmd.Parameters.Add(pDescription);
OracleParameter pScriptText = new OracleParameter();
pScriptText.ParameterName = "pSCRIPT_TEXT";
pScriptText.SourceColumn = "SCRIPT_TEXT";
ocmd.Parameters.Add(pScriptText);
}
private DataSet BuildCLOBTestDataSet()
{
DataSet ads = new DataSet();
DataTable at = new DataTable("CLOBTEST");
DataColumn ac = at.Columns.Add("ACTION_CODE", typeof(string));
at.Columns.Add("DESCRIPTION", typeof(string));
at.Columns.Add("SCRIPT_TEXT", typeof(string));
at.PrimaryKey = new DataColumn[] { ac };
ads.Tables.Add(at);
return ads;
}
private OracleConnection OpenConnection()
{
OracleConnection oc = null;
try
{
OracleClientFactory ocf = new OracleClientFactory();
DbConnectionStringBuilder csb = ocf.CreateConnectionStringBuilder();
csb["Data Source"] = _ServerName;
csb["User ID"] = _UserName;
csb["Password"] = _Password;
string cs = csb.ConnectionString;
oc = new OracleConnection(cs);
oc.Open();
AddLogMessage("Connection opened.");
}
catch (Exception ex)
{
AddLogMessage("Error Opening Connection! " + ex.Message);
throw;
}
return oc;
}
private void AddLogMessage(string msg)
{
Debug.WriteLine(string.Format("{0:T} - {1}", DateTime.Now, msg));
}
}
Two workarounds are shown in this thread: https://community.oracle.com/thread/3649551
Workaround one:
Configure your CLOB parameters as OracleDbType.Clob and ParameterDirection.InputOutput.
Workaround two:
Configure your CLOB parameters as OracleDbType.Clob and explicitly set the value to a OracleClob object.
Fix:
The bug is now known to Oracle, so hopefully a fixed version will be released soon.
Edit: Patch 20361140 should fix it.
This is how it works. I select a row from my listview then I will click "Edit" button which the values from the selected item will also be shown in the registration form. The "Register" button will now then changed to "Update". I am trying to update my customers table after changing inputs from the textboxes on my registration form but there are no changes in my database.
I receive no errors but I might have missed something here.
This is my code here:
private void btnRfrsh_Click(object sender, EventArgs e)
{
try
{
con = "datasource=localhost; port=3306; database=cam_air_db; uid=root;";
connect = new MySqlConnection(con);
connect.Open();
string query = "SELECT Cust_Lname, Cust_Fname, Cust_MI, Birthdate, Age, Sex, Passport_ID, Address, Contact_Num, Nationality from customers where removed = 0";
MySqlCommand select = new MySqlCommand(query, connect);
MySqlDataReader refresh = select.ExecuteReader();
while (refresh.Read())
{
ListViewItem item;
item = new ListViewItem(refresh.GetString(0));
item.SubItems.Add(refresh.GetString(1));
item.SubItems.Add(refresh.GetString(2));
item.SubItems.Add(refresh.GetString(3));
item.SubItems.Add(refresh.GetString(4));
item.SubItems.Add(refresh.GetString(5));
item.SubItems.Add(refresh.GetString(6));
item.SubItems.Add(refresh.GetString(7));
item.SubItems.Add(refresh.GetString(8));
item.SubItems.Add(refresh.GetString(9));
lviewCust.Items.Add(item);
}
if (refresh.Read())
{
connect.Close();
}
else
{
connect.Close();
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
private void btnEdit_Click(object sender, EventArgs e)
{
if (lviewCust.SelectedItems.Count > 0)
{
ListViewItem item = lviewCust.SelectedItems[0];
cust_fname.Text = item.SubItems[0].Text;
cust_lname.Text = item.SubItems[1].Text;
cust_mi.Text = item.SubItems[2].Text;
//DateTime bdate = Convert.ToDateTime(item.SubItems[3].Text);
String bdate_string = item.SubItems[3].Text;
DateTime bdate = DateTime.ParseExact(bdate_string, "dd-MM-yyyy", null);
cust_bdate.Value = bdate;
cust_age.Text = item.SubItems[4].Text;
cust_sex.Text = item.SubItems[5].Text;
cust_passid.Text = item.SubItems[6].Text;
cust_nation.Text = item.SubItems[9].Text;
cust_add.Text = item.SubItems[7].Text;
cust_contact.Text = item.SubItems[8].Text;
}
cust_fname.ReadOnly = true;
cust_lname.ReadOnly = true;
cust_mi.ReadOnly = true;
cust_passid.ReadOnly = true;
btnReg.Text = "Update";
btnReg.Name = "btnUpdate";
btnReg.Click -= this.btnReg_Click;
btnReg.Click += this.btnUpdate_Click;
}
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
con = "datasource=localhost; port=3306; database=cam_air_db; uid=root;";
connect = new MySqlConnection(con);
connect.Open();
string query = "UPDATE customers SET Age = '" + this.cust_age.Text + "', Nationality = '" + this.cust_nation.Text + "', Address = '" + this.cust_add.Text + "', Contact_Num = '" + this.cust_contact.Text + "' WHERE Cust_Fname = '" + this.cust_fname.Text + "' and Cust_Lname = '" + this.cust_lname.Text + "'";
MySqlCommand update = new MySqlCommand(query, connect);
MySqlDataReader updte = update.ExecuteReader();
MessageBox.Show("Customer Info Updated Successfully");
if (updte.Read())
{
connect.Close();
}
else
{
connect.Close();
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
cust_fname.Clear();
cust_lname.Clear();
cust_mi.Clear();
cust_bdate.Value = DateTime.Now;
cust_age.Clear();
cust_passid.Clear();
cust_add.Clear();
cust_contact.Clear();
cust_nation.Clear();
cust_fname.ReadOnly = false;
cust_lname.ReadOnly = false;
cust_mi.ReadOnly = false;
cust_passid.ReadOnly = false;
btnReg.Text = "Register";
btnReg.Name = "btnReg";
btnReg.Click -= this.btnUpdate_Click;
btnReg.Click += this.btnReg_Click;
}
}
}
First, I think you should use ExecuteNonQuery() instead of ExecuteReader().
You call ExecuteReader() when you execute a sql command that returns something (such as SELECT).
When you call a command that doesn't return anything (such as INSERT, UPDATE, DELETE, etc.), you should call ExecuteNonQuery().
See the details here.
Second, I think you should check the result before alert "successfully". ExecuteNonQuery() returns the number of rows affected, you can check this to determine success or not.
I have the following code which populates the Topic dropdownlist and saves it to a cached table:
bookingData2 = new DataTable();
DataTable DTable_List = new DataTable();
string connString = #"";
string query2 = #"Select * from [DB].dbo.[top]";// columng #1 = Specialty and column #2 = Topic
using (SqlConnection conn = new SqlConnection(connString))
{
try
{
SqlCommand cmd = new SqlCommand(query2, conn);
SqlDataAdapter da = new SqlDataAdapter(query2, conn);
da.Fill(bookingData2);
HttpContext.Current.Cache["cachedtable2"] = bookingData2;
bookingData2.DefaultView.Sort = "Topic ASC";
Topic.DataSource = bookingData2.DefaultView.ToTable(true, "Topic"); // populate only with the Topic column
Topic.DataTextField = "Topic";
Topic.DataValueField = "Topic";
Topic.DataBind();
Topic.Items.Insert(0, new ListItem("All Topics", "All Topics"));
da.Dispose();
}
catch (Exception ex)
{
string error = ex.Message;
}
}
I have the following code which populates the Specialty dropdownlist and saves it to another cached table:
bookingData = new DataTable();
DataTable DTable_List = new DataTable();
string connString = #"";
string query = #"select * from [DB].dbo.[SP]";
using (SqlConnection conn = new SqlConnection(connString))
{
try
{
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(query, conn);
da.Fill(bookingData);
bookingData.DefaultView.Sort = "Specialty ASC";
Specialty.DataSource = bookingData.DefaultView.ToTable(true, "Specialty");
Specialty.DataTextField = "Specialty";
Specialty.DataValueField = "Specialty";
Specialty.DataBind();
Specialty.Items.Remove("All Specialties");
Specialty.Items.Insert(0, new ListItem("All Specialties", "All Specialties"));
da.Dispose();
}
catch (Exception ex)
{
string error = ex.Message;
}
}
How can I code the Specialty dropdownlist index change to do the following and save it to a cache table for quick access:
protected void Specialty_SelectedIndexChanged(object sender, EventArgs e)
{
//re-populate the Topic dropdownlist to display all the topics based on the following criteria:
--> Where the Specialty column is either "All Specialties" OR "{specialty selected index value}"
}
Save bookingData2 table in ViewState or Session (I won't recommend to use session though) if it's not too heavy. Otherwise, its better you cache it or query the database again to repopulate it.
Let's assume you save bookingData2 in ViewState as follows in Page_Load
ViewState["bookingData2"] = bookingData2; // This should be before the following line
Topic.DataSource = bookingData2.DefaultView.ToTable(true, "Topic");
Then in your SelectedIndexChanged event do something like this
protected void Specialty_SelectedIndexChanged(object sender, EventArgs e)
{
//re-populate the Topic dropdownlist to display all the topics based on the following criteria:
// Where the Specialty column is either "All Specialties" OR "{specialty selected index value}"
DataTable bookingData2 = (DataTable)ViewState["bookingData2"];
Topic.DataSource = bookingData2.Where(i => i.Specialty == "All Specialties" || i.Specialty == Specialty.SelectedValue).DefaultView.ToTable(true, "Topic"); // populate only with the Topic column
Topic.DataTextField = "Topic";
Topic.DataValueField = "Topic";
Topic.DataBind();
Topic.Items.Insert(0, new ListItem("All Topics", "All Topics"));
}
Update - With Cached object
Do following in Specialty_SelectedIndexChanged event instead of where we used ViewState before.
if (HttpRuntime.Current.Cache["cachedtable2"] != null)
{
DataTable bookingData2 = HttpRuntime.Current.Cache["cachedtable2"] as DataTable;
// Rest of the code
}
I haven't tried this code. Let me know if you find any issues.
This is what solved it for me:
protected void Topic_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (Topic.SelectedIndex == 0)
{
string query = #"Specialty LIKE '%%'";
DataTable cacheTable = HttpContext.Current.Cache["cachedtable"] as DataTable;
DataTable filteredData = cacheTable.Select(query).CopyToDataTable<DataRow>();
filteredData.DefaultView.Sort = "Specialty ASC";
Specialty.DataSource = filteredData.DefaultView.ToTable(true, "Specialty");
Specialty.DataTextField = "Specialty";
Specialty.DataValueField = "Specialty";
Specialty.DataBind();
}
else
{
string qpopulate = #"[Topic] = '" + Topic.SelectedItem.Value + "' or [Topic] = 'All Topics'"; //#"Select * from [DB].dbo.[table2] where [Specialty] = '" + Specialty.SelectedItem.Value + "' or [Specialty] = 'All Specialties'";
DataTable cTable = HttpContext.Current.Cache["cachedtable2"] as DataTable;
DataTable fData = cTable.Select(qpopulate).CopyToDataTable<DataRow>();
if (fData.Rows.Count > 0)
{
fData.DefaultView.Sort = "Specialty ASC";
Specialty.DataSource = fData.DefaultView.ToTable(true, "Specialty");
Specialty.DataTextField = "Specialty";
Specialty.DataValueField = "Specialty";
Specialty.DataBind();
}
Specialty.Items.Insert(0, new ListItem("All Specialties", "All Specialties"));
}
}
catch (Exception ce)
{
string error = ce.Message;
}
}