Reading access database - c#

I have written code to return values based on a search box however at times, the value entered into the search box can apply to several records within an MSAccess DB.
Is there a way where I can scroll through the records that apply to the value in the search box by using a button?
public void LoopThroughRecs(OleDbDataReader Data)
{
Data.Read();
{
FirstName.Text = Data["Initial"].ToString();
LastName.Text = Data["Surname"].ToString();
Address1.Text = Data["Address 1"].ToString();
Address2.Text = Data["Address 2"].ToString();
Address3.Text = Data["Address 3"].ToString();
TownCity.Text = Data["Post Town"].ToString();
PostCode.Text = Data["Post Code"].ToString();
Telephone.Text = Data["Telephone"].ToString();
LstSvcDat.Text = Data["LastService"].ToString();
BoilerMan.Text = Data["Manufacturer"].ToString();
BoilerMod.Text = Data["Model"].ToString();
}
Data.Close();
}
public void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=BoilerSvc_be.mdb";
try
{
conn.Open();
OleDbCommand command = new OleDbCommand("SELECT CustCode,Initial,Surname,[Address 1],[Address 2],[Address 3],[Post Town],[Post Code],Telephone,Equipment.CustID AS CustID,Equipment.Manufacturer AS Manufacturer,Equipment.Model AS Model,Equipment.LastService AS LastService FROM Contacts LEFT OUTER JOIN Equipment ON Equipment.CustID = Contacts.CustID WHERE Archived = 0 AND (CustCode = '" + textBox12.Text + "' OR Initial = '" + textBox12.Text + "' OR Surname = '" + textBox12.Text + "' OR Initial = '" + textBox12.Text + "' OR [Post Town] = '" + textBox12.Text + "' OR [Post Code] = '" + textBox12 + "')", conn);
OleDbDataReader Data = command.ExecuteReader();
LoopThroughRecs(Data);
}
finally
{
conn.Close();
}
}

Related

No errors in the code, but no changes occur in the table when trying to update it

I'm trying to update my data in C# Win Form.
I created a button "update", but whenever I run it, I don't see any changes in the table and any occurring errors
void insertdata() {
cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM airport";
adapter.SelectCommand = cmd;
table.Clear();
adapter.Fill(table);
dgv.DataSource = table;
}
private void button_update_Click(object sender, EventArgs e)
{
cmd = connection.CreateCommand();
cmd.CommandText = "UPDATE airport SET p_name = '"+textBox2.Text+ "',p_age = '" + textBox3.Text + "', c_name = '" + textBox4.Text + "', date = '" + textBox5.Text + "', city_t = '" + textBox6.Text + "', city_f ='" + textBox7.Text + "', trip_num = '" + textBox8.Text + "', plane_type = '" + textBox9.Text+"' WHERE p_id = '"+textBox1+"'";
cmd.ExecuteNonQuery();
insertdata();
}
I've tried to add
connection.Open();
connection.Close();
However, I keep getting: "System.InvalidOperationException: "The connection was not closed. The connection is open."
Could there be any change in my code for updating the rows in the table, as whenever I run it I don't get any errors.
Please note the you wrote
WHERE p_id = '"+textBox1+"'
Instead of
WHERE p_id = '"+textBox1.Text+"'
Probably you don't have an ID that equals to the textBox...

Does not equal values in List

I have a datareader set up where it adds the Customer ID each time results are returned.
I have set up a 'next record' button which will run the same query but i want to set it so that the customer record returned does not equal the values stored in my list.
Is there a way to reference the list in a parameter for my MS Access query?
public void LoopThroughRecs(OleDbDataReader Reader)
{
List<int> customer = new List<int>();
while (Reader.Read())
{
int result;
CustID.Text = Reader["CustID"].ToString();
FirstName.Text = Reader["Initial"].ToString();
LastName.Text = Reader["Surname"].ToString();
Address1.Text = Reader["Address 1"].ToString();
Address2.Text = Reader["Address 2"].ToString();
Address3.Text = Reader["Address 3"].ToString();
TownCity.Text = Reader["Post Town"].ToString();
PostCode.Text = Reader["Post Code"].ToString();
Telephone.Text = Reader["Telephone"].ToString();
LstSvcDat.Text = Reader["LastService"].ToString();
BoilerMan.Text = Reader["Manufacturer"].ToString();
BoilerMod.Text = Reader["Model"].ToString();
result = Convert.ToInt32(CustID.Text);
customer.Add(int.Parse(CustID.Text));
}
}
public void SearchButton_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=BoilerSvc_be.mdb";
try
{
conn.Open();
OleDbCommand command = new OleDbCommand("SELECT Contacts.CustID AS CustID,CustCode,Initial,Surname,[Address 1],[Address 2],[Address 3],[Post Town],[Post Code],Telephone,Equipment.CustID AS CustID1,Equipment.Manufacturer AS Manufacturer,Equipment.Model AS Model,Equipment.LastService AS LastService FROM Contacts LEFT OUTER JOIN Equipment ON Equipment.CustID = Contacts.CustID WHERE Archived = 0 AND ([Address 1] = '" + textBox12.Text + "' OR CustCode LIKE '" + textBox12.Text + '%' + "' OR Initial = '" + textBox12.Text + '%' + "' OR Surname = '" + textBox12.Text + '%' + "' OR Initial = '" + textBox12.Text + '%' + "' OR [Post Town] LIKE '" + textBox12.Text + '%' + "' OR [Post Code] = '" + textBox12 + '%' + "')", conn);
OleDbDataReader Reader = command.ExecuteReader();
LoopThroughRecs(Reader);
}
finally
{
conn.Close();
}
}
public void NextRecord_Click_3(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=BoilerSvc_be.mdb";
try
{
conn.Open();
OleDbCommand command = new OleDbCommand("SELECT Contacts.CustID AS CustID,CustCode,Initial,Surname,[Address 1],[Address 2],[Address 3],[Post Town],[Post Code],Telephone,Equipment.CustID AS CustID1,Equipment.Manufacturer AS Manufacturer,Equipment.Model AS Model,Equipment.LastService AS LastService FROM Contacts LEFT OUTER JOIN Equipment ON Equipment.CustID = Contacts.CustID WHERE Archived = 0 AND Contacts.CustID <> #CustID AND ([Address 1] = '" + textBox12.Text + "' OR CustCode LIKE '" + textBox12.Text + '%' + "' OR Initial = '" + textBox12.Text + '%' + "' OR Surname = '" + textBox12.Text + '%' + "' OR Initial = '" + textBox12.Text + '%' + "' OR [Post Town] LIKE '" + textBox12.Text + '%' + "' OR [Post Code] = '" + textBox12 + '%' + "')", conn);
command.Parameters.Add(new OleDbParameter("#CustID" == Customer));
OleDbDataReader Reader = command.ExecuteReader();
LoopThroughRecs(Reader);
}
finally
{
conn.Close();
}
}

Textbox value does not get updated in asp.net

I have some Textboxes in my page. I am getting values from Database in and updating Textboxes in my page load. I have a code to update values in database behind update button. the problem is that when I change the textbox value and click update button, the value in textbox is again the original one. It retains its value. My code is
protected void Page_Load(object sender, EventArgs e)
{
int id = Convert.ToInt32(Session["DocumentID"]);
Connection conn = new Connection();
string query = "SELECT * from Document where DocumentID='" + id + "'";
SqlCommand sqlcom = new SqlCommand(query, conn.conopen());
SqlDataAdapter daexp = new SqlDataAdapter(sqlcom);
System.Data.DataTable dtexp = new System.Data.DataTable();
daexp.Fill(dtexp);
TextBox1.Text = dtexp.Rows[0][1].ToString();
TextBox3.Text = dtexp.Rows[0][2].ToString();
TextBox6.Text = dtexp.Rows[0][3].ToString();
TextBox4.Text = dtexp.Rows[0][4].ToString();
TextBox5.Text = dtexp.Rows[0][5].ToString();
TextBox7.Text = dtexp.Rows[0][6].ToString();
TextBox7.ReadOnly = true;
}
protected void Button1_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(Session["DocumentID"].ToString());
if (FileUpload1.HasFile)
{
HttpPostedFile Image = FileUpload1.PostedFile;
string contentType = Image.ContentType;
if (contentType.Equals("application/octet-stream"))
{
contentType = "application/pdf";
}
else if (contentType.Equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document"))
{
contentType = "application/msword";
}
int nFileLen = Image.ContentLength;
byte[] myData = new byte[nFileLen];
Image.InputStream.Read(myData, 0, nFileLen);
Connection con = new Connection();
con.conopen();
string query = "UPDATE Document SET Setup='" + TextBox1.Text + "', ReferenceNO='" + TextBox3.Text + "', DocumentDate='" + TextBox6.Text + "', Subject='" + TextBox4.Text + "', NameOfInitiator='" + TextBox5.Text + "', Document=#Doc, FolderID='" + DropDownList1.Text + "', DocTypeID='" + DropDownList4.Text + "', DirectorateID='" + DropDownList3.Text + "', OrganizationID='" + DropDownList2.Text + "' WHERE DocumentID='" + id + "'";
SqlCommand sqlcom = new SqlCommand(query, con.conopen());
sqlcom.Parameters.AddWithValue("#Doc", myData);
sqlcom.ExecuteNonQuery();
Label12.Text = "Document Updated Successfully";
Label12.ForeColor = System.Drawing.Color.Green;
Label12.Visible = true;
Label12.Text = "Document Updated Successfully";
Label12.ForeColor = System.Drawing.Color.Green;
Label12.Visible = true;
}
else
{
Connection conn = new Connection();
string query = "UPDATE Document SET Setup='" + TextBox1.Text + "', ReferenceNO='" + TextBox3.Text + "', DocumentDate='" + TextBox6.Text + "', Subject='" + TextBox4.Text + "', NameOfInitiator='" + TextBox5.Text + "', FolderID='" + DropDownList1.Text + "', DocTypeID='" + DropDownList4.Text + "', DirectorateID='" + DropDownList3.Text + "', OrganizationID='" + DropDownList2.Text + "' WHERE DocumentID='" + id + "'";
SqlCommand sqlcom = new SqlCommand(query, conn.conopen());
sqlcom.ExecuteNonQuery();
}
}
You are updating the values of Textboxes from database in your Page_Load. Every time page is posted back it gets values from database and sets in TextBoxes. You need to add a check and only update values and set to TextBoxes if page is loaded first time and not posted back. Like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
//your code here...
}
}
I know: Order Event of asp.net PreInit -Init -InitComplete -PreLoad -LoadPage -Control events -LoadComplete -PreRender -SaveStateComplete -Render -Unload
Therefore , When u onckick button, Webpage will ispostback. after, call pageload -> EventButton. value of textbox change, because your pageload set value for textbox.
Edit code:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack){
int id = Convert.ToInt32(Session["DocumentID"]);
Connection conn = new Connection();
string query = "SELECT * from Document where DocumentID='" + id + "'";
SqlCommand sqlcom = new SqlCommand(query, conn.conopen());
SqlDataAdapter daexp = new SqlDataAdapter(sqlcom);
System.Data.DataTable dtexp = new System.Data.DataTable();
daexp.Fill(dtexp);
TextBox1.Text = dtexp.Rows[0][1].ToString();
TextBox3.Text = dtexp.Rows[0][2].ToString();
TextBox6.Text = dtexp.Rows[0][3].ToString();
TextBox4.Text = dtexp.Rows[0][4].ToString();
TextBox5.Text = dtexp.Rows[0][5].ToString();
TextBox7.Text = dtexp.Rows[0][6].ToString();
TextBox7.ReadOnly = true;
}
}
Try to refer to the value Attribute:
TextBox1.Attributes("value")

Not able to read the text box value

I am assigning the value to the variable from the text box on the page during the pageupload event of AjaxFileUpload1.The problem is that, I am not getting the value from the text box to my variable even though no error throws.My variables are
string scn = txtSCN.Text;
string line1 = txtLineitem.Text;
string aging1 = txtAging.Text;
Any idea why AjaxFileUpload1_UploadComplete is not able to read text box value
My cs Code is:
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
string c = System.IO.Path.GetFileName(e.FileName);
string dpath = "~/Profile/Images/";
string scn = txtSCN.Text;
string line1 = txtLineitem.Text;
string aging1 = txtAging.Text;
AjaxFileUpload1.SaveAs(MapPath(Path.Combine(dpath,c)));
dpath = dpath + c;
string str1 = ConfigurationManager.ConnectionStrings["ProTracConnGMCH"].ConnectionString;
SqlConnection cn = new SqlConnection(str1);
cn.Open();
string sql = "Update tbNoquoteFollowupupdate set MailreceivedURL = '" + dpath + "', chkMailreceived = 1 , Buyername = '" + buyername + "' where scn = '" + scn + "' AND lineItem = '" + line1 + "' and Aging ='" + aging1 + "' ";
SqlCommand cmd = new SqlCommand(sql, cn);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
// AjaxFileUpload1.SaveAs(Path.Combine(dpath, e.FileName));
//AjaxFileUpload1.SaveAs(MapPath(dpath));
}
cn.Close();
BindGridviewData1();
cn.Open();
string cmd2 = "Insert Into tbMulitmailsreived (scn, lineItem,followupdate, Aging,MailreceivedURL) Values ('" + scn + "', '" + line1 + "','" + DateTime.Now + "','" + aging1 + "','" + dpath + "')";
SqlCommand sqlCommand2 = new SqlCommand(cmd2, cn);
sqlCommand2.ExecuteNonQuery();
cn.Close();
}
Please help me
I spent some time last week investigating this question but in the end couldn't find an easy solution for this. The OP in that question solved it by storing values in the Session but for this to work you would still need to cause a postback at some stage.
There apparently was functionality planned for the AjaxFileUpload control to pass values in the Context Keys collections but this was never implemented. This question describes how to implement this yourself though.
I think I saw another question around the same topic and the OP solved it by changing to using the AsyncFileUpload control but I stand to be corrected...
i think you need to add !Page.IsPostBack to your code. like this
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
if(!Page.IsPostBack)
{
string c = System.IO.Path.GetFileName(e.FileName);
string dpath = "~/Profile/Images/";
string scn = txtSCN.Text;
string line1 = txtLineitem.Text;
string aging1 = txtAging.Text;
AjaxFileUpload1.SaveAs(MapPath(Path.Combine(dpath,c)));
dpath = dpath + c;
string str1 = ConfigurationManager.ConnectionStrings["ProTracConnGMCH"].ConnectionString;
SqlConnection cn = new SqlConnection(str1);
cn.Open();
string sql = "Update tbNoquoteFollowupupdate set MailreceivedURL = '" + dpath + "', chkMailreceived = 1 , Buyername = '" + buyername + "' where scn = '" + scn + "' AND lineItem = '" + line1 + "' and Aging ='" + aging1 + "' ";
SqlCommand cmd = new SqlCommand(sql, cn);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
// AjaxFileUpload1.SaveAs(Path.Combine(dpath, e.FileName));
//AjaxFileUpload1.SaveAs(MapPath(dpath));
}
cn.Close();
BindGridviewData1();
cn.Open();
string cmd2 = "Insert Into tbMulitmailsreived (scn, lineItem,followupdate, Aging,MailreceivedURL) Values ('" + scn + "', '" + line1 + "','" + DateTime.Now + "','" + aging1 + "','" + dpath + "')";
SqlCommand sqlCommand2 = new SqlCommand(cmd2, cn);
sqlCommand2.ExecuteNonQuery();
cn.Close();
}
}

Updating Database on button click

i have a button that suppose to update data into the database.
private void button4_Click(object sender, EventArgs e)
{
//need update code//
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
SqlDataAdapter daCount = new SqlDataAdapter("select iCount from ComDet where cName = #cName", conn);
daCount.SelectCommand.Parameters.Add("#cName", SqlDbType.VarChar).Value = ListU.SelectedValue;
DataTable dtC = new DataTable();
daCount.Fill(dtC);
DataRow firstRow = dtC.Rows[0];
string x = firstRow["iCount"].ToString();
int y = Int32.Parse(x);
int z = y + 1;
//SqlCeCommand cmdC = conn.CreateCommand();
SqlCommand cmdC = conn.CreateCommand();
cmdC.CommandText = "Update ComDet set iCount = '" + z + "', ViewTime = '" + lblTime.Text + "', LastView = '" + txtUser2.Text + "' Where cName = '" + ListU.SelectedValue.ToString() + "'";
conn.Close();
}
but i get this error..
can someone help?
update =
i've changed my code to
cmdC.CommandText = "Update ComDet set iCount = " + z + ", ViewTime = '" + lblTime.Text + "', LastView = '" + txtUser2.Text + "' Where cName = '" + ListU.SelectedValue.ToString() + "'";
but the problem now is that , there's no update.
the iCount in the database is an INT , value is 0.
There is also no update for the viewtime and lastview.
where did i go wrong now?
change this:
cmdC.CommandText = "Update ComDet set iCount = '" + z + "', ViewTime = '" + lblTime.Text + "', LastView = '" + txtUser2.Text + "' Where cName = '" + ListU.SelectedValue.ToString() + "'";
to
cmdC.CommandText = "Update ComDet set iCount = " + z + ", ViewTime = '" + lblTime.Text + "', LastView = '" + txtUser2.Text + "' Where cName = '" + ListU.SelectedValue.ToString() + "'";
you dont need the "'" apostrophe around it becuase its a number. That would definitely get you string not in correct format error
I would guess maybe the icount value is not a number, i would recommend using TryParse just in case. And that should keep this error from happening. What to do about a bad value getting returned by the query is another issue.
private void button4_Click(object sender, EventArgs e)
{
//need update code//
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
SqlDataAdapter daCount = new SqlDataAdapter("select iCount from ComDet where cName = #cName", conn);
daCount.SelectCommand.Parameters.Add("#cName", SqlDbType.VarChar).Value = ListU.SelectedValue;
DataTable dtC = new DataTable();
daCount.Fill(dtC);
DataRow firstRow = dtC.Rows[0];
string x = firstRow["iCount"].ToString();
int y = 0;
if(Int32.TryParse(x,out y))
{
System.Diagnostics.Debug.WriteLine("iCount was an valid int32");
int z = y + 1;
//SqlCeCommand cmdC = conn.CreateCommand();
SqlCommand cmdC = conn.CreateCommand();
cmdC.CommandText = "Update ComDet set iCount = " + z + ", ViewTime = '" + lblTime.Text + "', LastView = '" + txtUser2.Text + "' Where cName = '" + ListU.SelectedValue.ToString() + "'";
}
else
System.Diagnostics.Debug.WriteLine("iCount was NOT a valid int32, value: " + x);
conn.Close();
}
Have you checked the value of the 'x' variable? The exception informs that the value of X isn't a valid integer, so the FormatException is thrown.

Categories