Access table update fail - c#

I use the following code to fill a DataGridView from an Access Database. After a Save button is clicked if the Data Grid is updated, the Database saves the data.
The strange thing is that this works for 2 out of 3 Data Tables. For the last one it throws an exception:
Syntax error in INSERT INTO statement
public Tables(string tabName)
{
InitializeComponent();
this.Text = tabName;
this.query = string.Format("SELECT *" + " FROM [{0}]", tabName);
conn.Open();
detailTable = new DataTable();
string tableName = tabName;
string query = string.Format("SELECT * FROM [{0}]", tableName);
OleDbDataAdapter detailAdapter = new OleDbDataAdapter(query, conn);
if (detailAdapter != null)
{
detailAdapter.Fill(detailTable);
}
DataGridView.DataSource = detailTable;
conn.Close();
}
private void BtnSave_Click(object sender, EventArgs e)
{
OleDbCommand comm = new OleDbCommand(query, conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(comm);
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
adapter.Update(detailTable);
}
Even if the words are reserved keywords (although I searched them) there is no way of that to be the issue.
More information the tabName can be "Partners", "Salaries", "Descriptions" and "Accounts". It doesn't work only on "Partners".

Okay, turns out I was wrong and I apologize for my stubbornness. The problem was in the e-mail column and I did not see why it had a problem with the dash mark.

Related

How to get data from SQL and write it in textbox?

I need a help.
I searched and I tried a lot but I am too bad to make it work on my project by myself.
This is code for button-Seek. I want to make Seek-button to fill textbox by respective data.
private void SeekClick(object sender, EventArgs e)
{
if (TBCusNumber.Text != "")
{
string Number = TBCusNumber.Text;
var Conn = new SqlConnection();
Conn.ConnectionString = ConfigurationManager.ConnectionStrings["WindowsFormsApp1.Properties.Settings.DataBase"].ConnectionString;
var Cmd = new SqlCommand();
Cmd.Connection = Conn;
Cmd.CommandText = "SELECT * FROM CustomerList WHERE CustomerNumber = " + Number;
var DataAdapter = new SqlDataAdapter(Cmd);
DataSet DataSet = new DataSet();
DataAdapter.Fill(DataSet, "CustomerList");
CusView.DataSource = DataSet;
CusView.DataMember = "CustomerList";
}
}
And This is the data table.
This is what happens when I put 3 in the text box and press Seek-button.
So here, I want all text boxes to be filled by the data which I searched.
You will get only one row for the query right?
So give like that,
txtFirstName.Text = DataSet.Tables[0].Rows[0]["FirstName"].ToString();
txtLasttName.Text = DataSet.Tables[0].Rows[0]["LastName"].ToString();
Like this you need to assign the values to the respective text boxes.
There are three problem need to fix.
You forget to open the connection with DB,add Conn.Open(); before you excute sql command.
You need to add parameter to prevention SQL Injection
Please use using it will help you to use external resources to return the memory.
when the DataSet be filled you can get the data then fill in textbox
You can follow like this.
private void SeekClick(object sender, EventArgs e)
{
if (TBCusNumber.Text != "")
{
string Number = TBCusNumber.Text;
using (var Conn = new SqlConnection())
{
Conn.ConnectionString = ConfigurationManager.ConnectionStrings["WindowsFormsApp1.Properties.Settings.DataBase"].ConnectionString;
using (var Cmd = new SqlCommand())
{
Cmd.Connection = Conn;
Cmd.CommandText = "SELECT * FROM CustomerList WHERE CustomerNumber = #Number";
Cmd.Parameters.AddWithValue("#Number", Number);
//You miss to add Conn.Open()
Conn.Open();
using (var DataAdapter = new SqlDataAdapter(Cmd))
{
DataSet DataSet = new DataSet();
DataAdapter.Fill(DataSet, "CustomerList");
CusView.DataSource = DataSet;
CusView.DataMember = "CustomerList";
//when the DataSet be filled you can get the data then fill in textbox
txt_firstName.Text = DataSet.Tables[0].Rows[0]["FirstName"].ToString();
}
}
}
}
}

OleDbCommand select does not return expected rows

I have two Access tables, namely Projects, including the rows of projectTitle and partyID, and ProjectParty, including the rows of title and ID.
private void btnSearch_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=HesabKetab.accdb;Persist Security Info=False;";
//search in the database
OleDbCommand oleCmd = new OleDbCommand();
oleCmd.Connection = conn;
if (radioBtnByTitle.Checked)
{
oleCmd.CommandText = "SELECT * FROM Projects WHERE projectTitle=#projectTitle";
oleCmd.Parameters.AddWithValue("#projectTitle", txtProjectTitle.Text);
}
else if (radioBtnByParty.Checked)
{
oleCmd.CommandText = "SELECT * FROM Projects WHERE partyID=#partyID";
oleCmd.Parameters.AddWithValue("#partyID", comboParty.SelectedValue.ToString());
}
//execute query
OleDbDataAdapter ole_da = new OleDbDataAdapter(oleCmd);
DataTable dt= new DataTable();
try
{
conn.Open();
ole_da.Fill(dt);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
dataGridViewDisplaySearchResults.DataSource = dt;
conn.Close();
}
In the above code I am trying to retrieve the values of the Projects Access database table. The second if is successful and it loads the queried rows into DataGridView. But the first if (when true) does not return the expected values. In fact, it loads nothing into the DataGridView. I have no idea why the query does not work when I try to do the select based on projectTitle. I tried debugging but I got no clue which parameters were being passed to the select command. Where am I wrong?
instead txtProjectTitle.ToString() in the first condition, isn't it txtProjectTitle.Text

Fill ComboBox with Access DB data

I'm using Visual Studio 2010 and C# to create a windows form with a combobox that should contain employees initials. I have spent the last few days searching through every solution I can find and I still can not get my combobox to populate.
This is what I've got as of now:
public static void FillComboBox(string Query, System.Windows.Forms.ComboBox LoggedByBox)
{
using (var CONN = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\Documents\\Service Request Application\\bin\\Debug\\servicereq1.mdb"))
{
CONN.Open();
DataTable dt = new DataTable();
try
{
OleDbCommand cmd = new OleDbCommand(Query, CONN);
OleDbDataReader myReader = cmd.ExecuteReader();
dt.Load(myReader);
}
catch (OleDbException e)
{
Console.WriteLine(e.ToString());
Console.ReadLine();
return;
}
LoggedByBox.DataSource = dt;
LoggedByBox.ValueMember = "ID";
LoggedByBox.DisplayMember = "Initials";
}
}
Then I call it when the form loads
private void Form1_Load(object sender, EventArgs e)
{
FillComboBox("select ID, Initials from [Fixers and Testers]", LoggedByBox);
}
When I run the program, the combobox is still blank. I'm positive that my column names and table names are correct. Any suggestions?
I finally got my ComboBox filled and I wanted to share what I changed for anyone else who stumbles across this question in their searches. After spending a bit more time searching through other questions and MSDN, I was able to come up with this.
private void LoadComboLogged()
{
AppDomain.CurrentDomain.SetData("DataDirectory",#"\\prod\ServiceRequests");
string strCon = #"Provider=Microsoft.Jet.OLEDB.4.0;DataSource=|DataDirectory|\servicereq1.mdb";
try
{
using (OleDbConnection conn = new OleDbConnection(strCon))
{
conn.Open();
string strSql = "SELECT Initials FROM [Fixers and Testers] WHERE [Status] ='C'";
OleDbDataAdapter adapter = new OleDbDataAdapter(new OleDbCommand(strSql, conn));
DataSet ds = new DataSet();
adapter.Fill(ds);
loggedByComboBox.DataSource = ds.Tables[0];
loggedByComboBox.DisplayMember = "Initials";
loggedByComboBox.ValueMember = "Initials";
}
}
catch (Exception ex)
{
}
}
I also found that I needed to call
LoadComboLogged();
when I initialized my form. Without that line, the ComboBox would only show a blank dropdown list. Hope this helps someone else who runs into this problem.
Passing control to static method causing this issue. Instead of passing control to the method make that method returns the table and within the load method load the control.
SqlConnection con = new SqlConnection("Data Source=RUSH-PC\\RUSH;Initial Catalog=Att;Integrated Security=True");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select name from userinfo", con);
DataTable dt = new DataTable();
da.Fill(dt);
DataRow dr;
dr = dt.NewRow();
dt.Rows.InsertAt(dr, 1);
comboBox1.DisplayMember = "name";
comboBox1.ValueMember = "name";
comboBox1.DataSource = dt;
con.Close();
This may help you...
Good luck...:-)
Another possible solution would be to query and return a list of strings. Perhaps it may be less efficient, but it's what I used in a recent project of mine. Here's an example that would reside in a method, possibly called GetInitialsFromDatabase():
using(var conn = new MySqlConnection(connectionString)
{
conn.Open();
using(MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT Initials FROM [Fixers and Testers] WHERE [Status] ='C'";
MySqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
// initials is a List<String> previously defined (Assuming strings)
initials.Add(String.Format("{0}", reader[0]));
}
}
conn.Close();
}
And then return the initials List, and then in your GUI you could say:
comboBox1.DataSource = returnedList;
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;

Populating TextBox, The data type is not valid for the boolean operation

I got a ComboBox with a table as data source, ID as a value member and a name as a display member.
Selecting a name from the ComboBox should populate 6 TextBoxes with data.
Exception:
The data type is not valid for the boolean operation. [ Data type (if known) = int,Data type (if known) = nvarchar ]
Code:
void FillComboBox()
{
//Fill Combo Box
SqlCeDataAdapter da = new SqlCeDataAdapter(" SELECT CustomerID, Name FROM Customers", clsMain.con);
DataSet ds = new DataSet();
da.Fill(ds);
cBox1.DataSource = ds.Tables[0];
cBox1.ValueMember = "CustomerID";
cBox1.DisplayMember = "Name";
}
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
clsMain.con.ConnectionString = #"Data Source=|DataDirectory|\Database\Sales.sdf";
clsMain.con.Open();
FillComboBox();
}
private void btnSave_Click(object sender, EventArgs e)
{
//Save Button
SqlCeCommand cmd = new SqlCeCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = " INSERT INTO Customers (Name, Phone1, Phone2, Address, Notes) VALUES (#Name, #Phone1, #Phone2, #Address, #Notes) ";
cmd.Connection = clsMain.con;
cmd.Parameters.AddWithValue("#Name", txt2.Text.Trim());
if (txt3.Text != "")
{
cmd.Parameters.AddWithValue("#Phone1", Convert.ToInt32(txt3.Text));
}
else
{
cmd.Parameters.AddWithValue("#Phone1", Convert.DBNull);
}
if (txt4.Text != "")
{
cmd.Parameters.AddWithValue("#Phone2", Convert.ToInt32(txt4.Text));
}
else
{
cmd.Parameters.AddWithValue("#Phone2", Convert.DBNull);
}
cmd.Parameters.AddWithValue("#Address", txt5.Text.Trim());
cmd.Parameters.AddWithValue("#Notes", txt6.Text.Trim());
cmd.ExecuteNonQuery();
MessageBox.Show("Data stored.");
}
private void cBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (cBox1.SelectedIndex >= 0)
{
String Code = "SELECT * FROM Customers WHERE CustomerID=" + cBox1.SelectedValue.ToString();
SqlCeDataAdapter da = new SqlCeDataAdapter(Code, clsMain.con);
DataSet ds = new DataSet();
da.Fill(ds);
txt1.Text = ds.Tables[0].Rows[0]["CustomerID"].ToString();
txt2.Text = ds.Tables[0].Rows[0]["Name"].ToString();
txt3.Text = ds.Tables[0].Rows[0]["Phone1"].ToString();
txt4.Text = ds.Tables[0].Rows[0]["Phone2"].ToString();
txt5.Text = ds.Tables[0].Rows[0]["Address"].ToString();
txt6.Text = ds.Tables[0].Rows[0]["Notes"].ToString();
}
}
Table Details:
To follow up on my comment (with the caveat that I have never worked with SQL CE, but I'm pretty sure (99.9%) that this is correct).
In you SQL query string, you surround the customer id with single quotes ('). You use single quotes in SQL ("nomral" SQL at least) for character (char\varchar etc) and date values. You pass numeric values without single quotes.
You didn't indicate what line was giving you the exception, but based on the table structure and what you are doing (you gave good detail in your question, by the way), it seems that the error message is telling you that you're trying to compare an int to a varchar, and that's not allowed (because they are different data types, as the error indicates).
To resolve this, simply remove the single quotes from the value in your WHERE clause and construct your query as follows:
String Code = "SELECT * FROM Customers WHERE CustomerID=" + cBox1.SelectedValue;
Thank you, Its working for me.
I am having some customers name in comboBox2. Based on the selected name textbox will return CustomerID and Date of Allocation values.
Following are the code for that:
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if(comboBox2.SelectedIndex>0)
{
con = new SqlCeConnection(s);
con.Open();
string code = "select CustomerID,Date_of_Allocation from lockerdetails
where CustomerName='" + comboBox2.SelectedValue.ToString() + "'";
SqlCeDataAdapter da = new SqlCeDataAdapter(code, con);
SqlCeCommandBuilder cmd = new SqlCeCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds);
textBox1.Text = ds.Tables[0].Rows[0]["CustomerID"].ToString();
textBox5.Text = ds.Tables[0].Rows[0]["Date_of_Allocation"].ToString();
}
}
catch(SystemException se)
{
MessageBox.Show(se.Message);
}

Check if Column Value Exists in Dataset using C# and ASP

I've tried various solutions I have found and either I don't know how to implement them properly or they simply won't work. I have a method that allows someone to search a table for a specific order number, then the rest of the row will display in a gridview. However, if an order number is entered that doesn't exist in the table then I can get server error/exception. How can I make it so that before the search goes through or while the search goes through, if an order number that does't exist in the database is searched for then I can create the error instead?
I am using an ms access database, C#, and ASP.
Here is some of the code I am working with:
the method for searching the order table:
public static dsOrder SearchOrder(string database, string orderNum)
{
dsOrder DS;
OleDbConnection sqlConn;
OleDbDataAdapter sqlDA;
sqlConn = new OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + database);
DS = new dsOrder();
sqlDA = new OleDbDataAdapter("select * from [Order] where order_num='" + orderNum + "'" , sqlConn);
sqlDA.Fill(DS.Order);
return DS;
}
And using that method:
protected void btnSearch_Click(object sender, EventArgs e)
{
Session["OrderNum"] = txtSearch.Text;
Session["ddl"] = ddlSearch.Text;
if (Session["ddl"].ToString() == "Order")
{
dsOrder dataSet2;
dataSet2 = Operations.SearchOrder(Server.MapPath("wsc_database.accdb"), Session["OrderNum"].ToString());
grdSearch.DataSource = dataSet2.Tables["Order"];
grdSearch.DataBind();
}
Do I need to do a try/catch?
A huge thanks in advance to who is able to help me!
You can simply do a check to see whether DataSet is empty
if (dataSet2 == null || dataSet2.Tables.Count == 0 || dataSet2.Tables["Order"] == null || dataSet2.Tables["Order"].Rows.Count == 0)
{
//display error to user
}
else
{
// your code to populate grid
}
If you don't want to show error then just put this check before populating GridView
if (dataSet2.Tables != null && dataSet2.Tables["Order"] != null)
{
// your code to populate grid
}
I use a different approach when filling data grids and always use parameters as follows:
public static DataTable GetGridDatasource(string database, string ordnum) {
using (OleDbConnection con = new OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source=" + database))
{
con.Open();
OleDbCommand cmd = con.CreateCommand();
cmd.CommandText = "select * from [Order] where order_num=[OrderNumber]";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("OrderNumber", ordnum);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
Session["OrderNum"] = txtSearch.Text;
Session["ddl"] = ddlSearch.Text;
if (Session["ddl"].ToString() == "Order")
{
grdSearch.DataSource = GetGridDatasource(Server.MapPath("wsc_database.accdb"), Session["OrderNum"].ToString());
}
}

Categories