I'm having an issue with either the reader being open when I try to use the same connection to add data to the database OR closing or disposing the reader and having the program freeze.
If you don't understand what i'm trying to explain, please ask questions. I'm a bit confused by the whole thing so I might be making 0 sense.
Code:
private void btnRegister_Click(object sender, EventArgs e)
{
int numerror = 0;
if (RUsernameTextBox.Text == "")
{
numerror++;
}
if (RPasswordTextBox.Text == "")
{
numerror++;
}
if (REmailTextBox.Text == "")
{
numerror++;
}
if (numerror > 0)
{
ErrorLabel.Text = "*" + numerror + " required field" + (numerror != 1 ? "s are" : " is") + " blank.";
}
else
{
var constring = "datasource=localhost;port=3306;username=Admin;password=**********;";
using (var con = new MySqlConnection(constring))
{
con.Open();
var cmd0 = new MySqlCommand("select username from userinfo.users where username=#username");
cmd0.CommandType = CommandType.Text;
cmd0.Connection = con;
cmd0.Parameters.AddWithValue("#username", RUsernameTextBox.Text);
using (var reader = cmd0.ExecuteReader())
{
if (reader.HasRows)
{
CMessageBox("Error", "Username is already in use.");
reader.Close();
}
else
{
reader.Close();
var HashedPassword = EncodePassword(RPasswordTextBox.Text);
var cmd = new MySqlCommand("INSERT INTO userinfo.users (username,password,email,premium,picture) VALUES (#username, #hashedpassword, #email , #premium , #picture);");
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Username", RUsernameTextBox.Text);
cmd.Parameters.AddWithValue("#hashedpassword", HashedPassword);
cmd.Parameters.AddWithValue("#email", REmailTextBox.Text);
cmd.Parameters.AddWithValue("#premium", "0");
cmd.Parameters.AddWithValue("#picture", "ftp://***.***.*.**/Profile Pictures/" + RUsernameTextBox.Text + "/" + Path.GetFileNameWithoutExtension(RProfilePicture.ImageLocation) + ".png");
try
{
cmd.ExecuteNonQuery();
MakeLoginVisible();
var TempFolder = Path.GetTempPath();
RProfilePicture.Image.Save("C:\\temp\\" + Path.GetFileNameWithoutExtension(RProfilePicture.ImageLocation) + ".png", System.Drawing.Imaging.ImageFormat.Png);
var ftpclient = new ftp("ftp://***.***.*.**/", "Admin", "**********");
ftpclient.createDirectory("Profile Pictures/" + RUsernameTextBox.Text);
ftpclient.upload("Profile Pictures/" + RUsernameTextBox.Text + "/" + Path.GetFileNameWithoutExtension(RProfilePicture.ImageLocation) + ".png", "C:\\temp\\" + Path.GetFileNameWithoutExtension(RProfilePicture.ImageLocation) + ".png");
MakeLoginVisible();
CMessageBox("Success!", "AirSpace Account '" + RUsernameTextBox.Text + "' Created.");
ftpclient = null;
con.Close();
}
catch (Exception ex)
{
CMessageBox("Error", ex.Message.ToString());
}
}
}
}
}
}
using (var con = new MySqlConnection(constring))
using(var cmd0 = new MySqlCommand("Select count(*) from userinfo.users where username=#username", con))
{
con.Open();
cmd0.Parameters.AddWithValue("#username", RUsernameTextBox.Text);
if((int)cmd0.ExecuteScalar() > 0)
{
CMessageBox("Error", "Username is already in use.");
return;
}
}
using (var con = new MySqlConnection(constring))
using(var cmd= new MySqlCommand("INSERT INTO userinfo.users (username,password,email,premium,picture) VALUES (#username, #hashedpassword, #email , #premium , #picture)", con))
{
con.Open();
var HashedPassword = EncodePassword(RPasswordTextBox.Text);
cmd.Parameters.AddWithValue("#Username", RUsernameTextBox.Text);
cmd.Parameters.AddWithValue("#hashedpassword", HashedPassword);
cmd.Parameters.AddWithValue("#email", REmailTextBox.Text);
cmd.Parameters.AddWithValue("#premium", "0");
cmd.Parameters.AddWithValue("#picture", "ftp://***.***.*.**/Profile Pictures/" + RUsernameTextBox.Text + "/" + Path.GetFileNameWithoutExtension(RProfilePicture.ImageLocation) + ".png");
try
{
cmd.ExecuteNonQuery();
MakeLoginVisible();
var TempFolder = Path.GetTempPath();
RProfilePicture.Image.Save("C:\\temp\\" + Path.GetFileNameWithoutExtension(RProfilePicture.ImageLocation) + ".png", System.Drawing.Imaging.ImageFormat.Png);
var ftpclient = new ftp("ftp://***.***.*.**/", "Admin", "**********");
ftpclient.createDirectory("Profile Pictures/" + RUsernameTextBox.Text);
ftpclient.upload("Profile Pictures/" + RUsernameTextBox.Text + "/" + Path.GetFileNameWithoutExtension(RProfilePicture.ImageLocation) + ".png", "C:\\temp\\" + Path.GetFileNameWithoutExtension(RProfilePicture.ImageLocation) + ".png");
MakeLoginVisible();
CMessageBox("Success!", "AirSpace Account '" + RUsernameTextBox.Text + "' Created.");
ftpclient = null;
}
catch (Exception ex)
{
CMessageBox("Error", ex.Message.ToString());
}
}
You don't really need a reader in this case. You can just get the count in your query and use ExecuteScalar()
var cmd0 = new MySqlCommand("select count(*) from userinfo.users where username=#username");
cmd0.CommandType = CommandType.Text;
cmd0.Connection = con;
cmd0.Parameters.AddWithValue("#username", RUsernameTextBox.Text);
if (((int)cmd0.ExecuteScalar()) > 0)
CMessageBox("Error", "Username is already in use.");
else
... the rest of the code
Related
My code
public void SaveEdits()
{
string SQL = "UPDATE SURVEY_CAMPAIGN SET OUTGOING_VDN =" + txtOutgoing.Value + "AND LANG_CD =" + txtlang.Value + "AND ANNOUNCEMENT_FOLDER =" + txtAnnouc.Value + "AND EXCEEDED_AUDIO =" + txtExceed.Value + "AND VALID_ENTRY_AUDIO =" + txtExit.Value +
" WHERE CAMPAIGN_ID =" + CampignsDRP.SelectedValue;
try
{
using (OracleConnection conn = SingleConnection.Instance.ActiveConn)
{
conn.Open();
OracleCommand cmd = conn.CreateCommand();
OracleDataAdapter dataAdapter = new OracleDataAdapter(SQL, conn);
System.Data.DataSet db = new System.Data.DataSet();
cmd.CommandType = CommandType.Text;
cmd.CommandText = SQL;
int result = cmd.ExecuteNonQuery();
dataAdapter.Fill(db, "Campaign");
cmd.Dispose();
conn.Close();
}
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "UpdateCompleted()", true);
}
catch (Exception ex)
{
string error = ex.Message;
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "ShowError('" + error + "')", true);
LogUtil.Debug("Page Campaign Update Exception Occured " + ex.Message);
}
}
string SQL = "UPDATE SURVEY_CAMPAIGN SET OUTGOING_VDN = #OUTGOING_VDN, LANG_CD = #LANG_CD, ANNOUNCEMENT_FOLDER = #ANNOUNCEMENT_FOLDER, EXCEEDED_AUDIO = #EXCEEDED_AUDIO, VALID_ENTRY_AUDIO = #VALID_ENTRY_AUDIO WHERE CAMPAIGN_ID = #CAMPAIGN_ID" ;
//Now put this parameters before int result = cmd.ExecuteNonQuery();
cmd.Parameters.AddWithValue("#OUTGOING_VDN", txtOutgoing.Text);
cmd.Parameters.AddWithValue("#LANG_CD", txtlang.Text);
cmd.Parameters.AddWithValue("#ANNOUNCEMENT_FOLDER",
txtAnnouc.Text);
cmd.Parameters.AddWithValue("#EXCEEDED_AUDIO", txtExceed.Text);
cmd.Parameters.AddWithValue("#VALID_ENTRY_AUDIO", txtExit.Text);
cmd.Parameters.AddWithValue("#CAMPAIGN_ID", CampignsDRP.SelectedValue);
I'm a beginner in C# and I have a problem with image uploading.
Everything in my code inserting in my database except for the files that I uploaded, I didn't know why it doesn't save it in the database, it only saved when I remove the Response.Redirect("Personalinformation.aspx") but I can't remove this response redirect because I need it.
protected void Button8_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conString);
con.Open();
if (con.State == System.Data.ConnectionState.Open)
{
if (TextBox11.Text != "" && TextBox8.Text != "" && TextBox9.Text != "" )
{
if (FileUpload1.PostedFile != null)
{
if (FileUpload2.PostedFile != null)
{
string FileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
string FileName1 = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
//Save files to disk
FileUpload1.SaveAs(Server.MapPath("/upload/" + FileName));
FileUpload2.SaveAs(Server.MapPath("/identification/" + FileName1));
String q = "Insert into dbo.requests(request_type,visit_date,reason,request_date,status_id,user_id,user_name,FileName,FilePath,End_vdate,FileName1,FilePath1,RequestNotes,VisitorType)values(N'" + DropDownList1.SelectedValue + "',N'" + TextBox8.Text + "',N'" + TextBox9.Text + "','" + DateTime.Now + "','4','" + Session["empNo"] + "',N'" + Session["ArbnName"] + "' , #FileName , #FilePath ,N'" + TextBox10.Text + "',#FileName1 , #FilePath1)";
SqlCommand cmd = new SqlCommand(q, con);
cmd.Parameters.AddWithValue("#FileName", FileName);
cmd.Parameters.AddWithValue("#FilePath", "/upload/" + FileName);
cmd.Parameters.AddWithValue("#FileName1", FileName1);
cmd.Parameters.AddWithValue("#FilePath1", "/identification/" + FileName1);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
else
{
String q = "Insert into dbo.requests(request_type,visit_date,reason,request_date,status_id,user_id,user_name,End_vdate,phone_ext)values(N'" + DropDownList1.SelectedValue + "',N'" + TextBox8.Text + "',N'" + TextBox9.Text + "','" + DateTime.Now + "','4','" + Session["empNo"] + "' ,N'" + Session["ArbnName"] + "',N'" + TextBox10.Text + "','" + TextBox11.Text.ToString() + "')";
SqlCommand cmd = new SqlCommand(q, con);
cmd.ExecuteNonQuery();
}
response.redirect("Personalinformation.aspx");
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Scripts", "<script>alert(' هناك حقول مطلوبة فارغة ');</script>");
}
String c = "Insert into dbo.logFile(user_id,transaction_date,action_type) values ('" + Session["empNo"] + "', '" + DateTime.Now + "' ,N' طلب قبول زائر') ";
SqlCommand cmdc = new SqlCommand(c, con);
cmdc.ExecuteNonQuery();
con.Close();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex == 0) //index of long visit
{
FileUpload1.Visible = false;
FileUpload2.Visible = false;
Button6.Visible = false;
TextBox10.Visible = false;
Label2.Visible = false;
Label3.Visible = false;
}
else
{
FileUpload1.Visible = true;
FileUpload2.Visible = true;
Button6.Visible = true;
TextBox10.Visible = true;
Label2.Visible = true;
Label3.Visible = true;
}
}
Instead of Response.Redirect, you can try using Server.Transfer if you intend to transfer the user to other page.
See more details at difference between Server.Transfer and Response.Redirect?
You have used FileUpload1.SaveAs:
FileUpload1.SaveAs(Server.MapPath("/upload/" + FileName));
FileUpload2.SaveAs(Server.MapPath("/identification/" + FileName1));
Instead of that use this:
FileUpload1.PostedFile.SaveAs(Server.MapPath("/upload/" + FileName));
FileUpload2.PostedFile.SaveAs(Server.MapPath("/identification/" + FileName1));
You are missing PostedFile keyword in that.
How to fix this problem? I don't know why this error occur when I already add Clode().
The error will go here:
public void existType()
{
try
{
con.Open();
string existquery = "SELECT*FROM tblRoomType WHERE Type = '" + txtRoomType.Text + "'";
da = new OleDbDataAdapter(existquery, con);
da.Fill(ds, "tblRoomType");
int counter = 0;
string tabletype = "tblRoomType";
if (counter < ds.Tables[tabletype].Rows.Count)
{
string type = ds.Tables[tabletype].Rows[counter]["Type"].ToString();
if (type == txtRoomType.Text)
{
editRoomType(); //There will be no error if I remove this and include the MessageBox below.
MessageBox.Show("Successfully Edited", "SUCCESS", MessageBoxButtons.OK, MessageBoxIcon.Information);
//MessageBox.Show("This " + txtRoomType.Text + " is already exist.", "EXIST", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else //Remove this will remove the error
{
addRoomType();
MessageBox.Show("Successfully Added", "SUCCESS", MessageBoxButtons.OK, MessageBoxIcon.Information);
}//to here
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This are the code of editRoomType() and addRoomType():
public void addRoomType()
{
con.Open();
string addtypequery = "INSERT INTO tblRoomType VALUES ('" + this.typeid + "','" + txtRoomType.Text + "','" + txtRoomRate.Text + "','" + txtExtraCharge.Text + "','" + txtCancelFee.Text + "','" + txtMaxOcc.Text + "')";
cmd = new OleDbCommand(addtypequery, con);
cmd.ExecuteNonQuery();
con.Close();
loadRoomType();
txtRoomType.ReadOnly = false;
txtRoomType.Enabled = false;
txtRoomRate.Enabled = false;
txtMaxOcc.Enabled = false;
txtExtraCharge.Enabled = false;
txtCancelFee.Enabled = false;
btnAddRoomType.Enabled = false;
txtRoomType.Clear();
txtRoomRate.Clear();
txtMaxOcc.Clear();
txtExtraCharge.Clear();
txtCancelFee.Clear();
}
public void editRoomType()
{
con.Open();
string edittypequery = "UPDATE tblRoomType SET Rate = '" + txtRoomRate.Text + "', ExtraCharge = '" + txtExtraCharge.Text + "', CancelFee = '" + txtCancelFee.Text + "', MaxOcc = '" + txtMaxOcc.Text + "' WHERE TypeID = '" + txtRoomType.Text + "'";
cmd = new OleDbCommand(edittypequery, con);
cmd.ExecuteNonQuery();
con.Close();
}
The existType() will be go here:
private void btnAddRoomType_Click(object sender, EventArgs e)
{
if (txtRoomType.Text != "" || txtRoomRate.Text != "" || txtExtraCharge.Text != "" || txtCancelFee.Text != "" || txtMaxOcc.Text != "")
{
existType();
}
else
{
MessageBox.Show("Please fill in the space provided","OOPPSS!!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
The error is because you call con.Open in existType, then you either call addRoomType or editRoomType, both of which call con.Open again before you call con.Close in existType. Calling con.Open on an already open connection will throw the error you are seeing.
You can either remove the calls to con.Open/con.Close inside of the addRoomType or editRoomType and only call them in existType, or use local connections for each method, like so:
public void existType()
{
try
{
using (var conn = new SqlConnection())
{
conn.Open();
string existquery = "SELECT*FROM tblRoomType WHERE Type = '" + txtRoomType.Text + "'";
da = new OleDbDataAdapter(existquery, conn);
da.Fill(ds, "tblRoomType");
}
//rest of code
}
}
public void editRoomType()
{
using (var conn = new SqlConnection())
{
conn.Open();
string edittypequery = "UPDATE tblRoomType SET Rate = '" + txtRoomRate.Text + "', ExtraCharge = '" + txtExtraCharge.Text + "', CancelFee = '" + txtCancelFee.Text + "', MaxOcc = '" + txtMaxOcc.Text + "' WHERE TypeID = '" + txtRoomType.Text + "'";
cmd = new OleDbCommand(edittypequery, conn);
cmd.ExecuteNonQuery();
}
}
Note that you don't have to call Close since the using statement will do that for you.
Try like this -
try
{
con.Open();
.......
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Open();
}
}
I'm working with a local database, and it works well, the whole app. The problem is that I'm facing with some annoying things. If I update, or add new data to my local database, I have to close the whole app and start it again so I can see the new data I have entered. Why is it not refreshing and how can I solve it?
Here is how I add data:
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked)
{
label5.Text = "1";
}
else
{
label5.Text = "0";
}
if (radioButton2.Checked)
{
label5.Text = "2";
}
if (textBox1.Text.Length == 0)
{
textBox1.Text = "Fara";
}
if (textBox2.Text.Length == 0)
{
textBox2.Text = "0";
}
if (textBox3.Text.Length == 0)
{
textBox3.Text = "0";
}
if (numeTextBox.TextLength != 0 && prenumeTextBox.TextLength != 0)
{
var connString = (#"Data Source=" + Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + #"\Angajati.sdf");
//var connString = #"Data Source=C:\Users\Andrei\Documents\Visual Studio 2010\Projects\Stellwag\Stellwag\Angajati.sdf";
using (var conn = new SqlCeConnection(connString))
{
try
{
//deschide conectiunea in db
conn.Open();
//creaza comanda in SQL Server CE
SqlCeCommand cmd = new SqlCeCommand();
//conecteaza cmd la conn
cmd.Connection = conn;
//adauga parametru pt campul poza cu value image
SqlCeParameter picture = new SqlCeParameter("#Poza", SqlDbType.Image);
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] a = ms.GetBuffer();
ms.Close();
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Poza", a);
cmd.CommandText = "INSERT INTO info(Nume, Prenume, Data, Proiect, Schimburi, Poza, Acord, Baza) VALUES('" + numeTextBox.Text.Trim() + "', '" + prenumeTextBox.Text.Trim() + "', '" + dateTimePicker1.Value.ToShortDateString() + "', '" + textBox1.Text.Trim() + "', " + label5.Text + " , #Poza, " + textBox2.Text + ", " + textBox3.Text + ");";
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Salvat cu succes!");
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
numeTextBox.Clear();
prenumeTextBox.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
else
{
MessageBox.Show("Trebuie sa completezi campurile inainte de a salva!");
}
}
Here is how I update it:
private void button1_Click_1(object sender, EventArgs e)
{
//var connString = (#"Data Source= |DataDirectory|\Angajati.sdf");
var connString = (#"Data Source=" + System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + #"\Angajati.sdf");
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
SqlCeCommand cmd = new SqlCeCommand();
//conecteaza cmd la conn
cmd.Connection = conn;
//adauga parametru pt campul poza cu value image
SqlCeParameter picture = new SqlCeParameter("#Poza", SqlDbType.Image);
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] a = ms.GetBuffer();
ms.Close();
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Poza", a);
var query = "UPDATE info SET Nume='" + textBox5.Text + "' , Prenume='" + textBox4.Text + "' , Data='" + dateTimePicker1.Value.ToShortDateString() + "', Proiect='" + textBox1.Text + "', Schimburi='" + label10.Text + "', Poza=#Poza, Acord='" + textBox2.Text + "', Baza='" + textBox3.Text + "' WHERE Nume='" + textBox5.Text + "' AND Prenume='" + textBox4.Text + "'";
cmd.CommandText = query;
cmd.ExecuteNonQuery();
MessageBox.Show("Salvat cu succes!");
this.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
Here is how I search data:
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Length != 0)
{
var numePrenume = textBox1.Text.Trim().Split(' ');
if (numePrenume.Count() > 1)
{
var nume = numePrenume[0];
var prenume = numePrenume[1];
var connString = (#"Data Source=" + System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + #"\Angajati.sdf");
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
var query = "SELECT COUNT(*) FROM info WHERE Nume='" + nume + "' AND Prenume='" + prenume + "'";
var command = new SqlCeCommand(query, conn);
var dataAdapter = new SqlCeDataAdapter(command);
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
//checks if there's the searched record is in the db.
int infoCount = (int)command.ExecuteScalar();
if (infoCount > 0)
{
Info form = new Info(nume, prenume);
form.Show();
}
else
{
MessageBox.Show("Nu exista un angajat cu acest nume");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
else
{
MessageBox.Show("Nu ai introdus prenumele");
}
}
else
{
MessageBox.Show("Nu ai introdus nici un nume!");
}
}
I have solved this problem by changing the path to the db, it was something wrong at it, and by creating a refresh function for my gridView called after the insert. Bellow is the code for the solution:
Getting the path like this now:
string startPath = Application.StartupPath;
var filepath = startPath + "\\" + "Grupe.sdf";
var connString = (#"Data Source=" + filepath +"");
The refresh function:
public void refresh()
{
var connString = (#"Data Source=" + System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + #"\Grupe.sdf");
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
var query = "SELECT * FROM copii";
var command = new SqlCeCommand(query, conn);
var dataAdapter = new SqlCeDataAdapter(command);
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
dataGridView1.DataSource = dataTable;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
//How to exceute multiple sqlcommands in one transaction in C#..i am using like this but it gives me error..plz let me know what is problem with code..
string[] files = Directory.GetFiles(dir);
foreach (string subfiles in files)
{
con.Open();
SqlTransaction myTrans=null;
myTrans= con.BeginTransaction();
try
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.Transaction = myTrans;
cmd.CommandText = "select descr from genlookup where Code='SS_Purchase_No' and RecId=99998";
SqlDataReader drr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable dt = new DataTable();
//SqlDataAdapter da = new SqlDataAdapter(qry1, con);
DataTable dtw = new DataTable();
dtw.Load(drr);
DataSet dsr = new DataSet();
dsr.Tables.Add(dtw);
//SqlDataAdapter darun = new SqlDataAdapter("select descr from genlookup where Code='SS_Purchase_No' and RecId=99998", con);
//DataSet dsr = new DataSet();
//darun.Fill(dsr);
int run_no = Convert.ToInt32(dsr.Tables[0].Rows[0]["descr"].ToString());
filename = Path.GetFileNameWithoutExtension(subfiles);
string filenames = Path.GetFileName(subfiles);
if (subfiles.Trim().EndsWith(".xlsx"))
{
strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", subfiles);
}
else if (subfiles.Trim().EndsWith(".xls"))
{
strConn = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", subfiles);
}
OleDbConnection exlcon = new OleDbConnection(strConn);
exlcon.Open();
string myTableName = exlcon.GetSchema("Tables").Rows[0]["TABLE_NAME"].ToString();
OleDbDataAdapter oledbadpt = new OleDbDataAdapter(String.Format("SELECT * FROM [{0}] ", myTableName), exlcon);
DataSet d_s = new DataSet();
oledbadpt.Fill(d_s);
exlcon.Close();
for (int i = 7; i < d_s.Tables[0].Rows.Count - 1; i++)
{
PARTNER_ID = d_s.Tables[0].Rows[i]["F1"].ToString();
RTV_LOCTN = d_s.Tables[0].Rows[i]["F3"].ToString();
DateTime date1 = Convert.ToDateTime(d_s.Tables[0].Rows[i]["F13"]);
string ddmm = date1.ToString("yyyyMMdd");
string[] aa = Color_size.Split('/');
// string colr="";
string size = "";
foreach (string ss in aa)
{
size = ss;
}
}
con.Open();
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = con;
myCommand.Transaction = myTrans;
myCommand.CommandText = "insert into HSR_Purch_RETURN(PARTNER_ID,RTV_LOCTN)" +
" values('" + PARTNER_ID + "'," + "'" + RTV_LOCTN + "') ";
myCommand.ExecuteNonQuery();
//con.Open();
//SqlCommand cmdd = new SqlCommand(insert, con);
//int value1 = cmdd.ExecuteNonQuery();
//values = string.Empty;
con.Close();
if ((shrwcode != "") && (flag == "F"))
{
string zz = "select DistributionCenter,GLCountry,GLZone,GLState,GLCity from showroommaster where ShowroomCode='" + shrwcode + "'";
SqlDataAdapter da11 = new SqlDataAdapter(zz, con);
DataSet ds11 = new DataSet();
da11.Fill(ds11);
string Dcenter = ds11.Tables[0].Rows[0]["DistributionCenter"].ToString();
string GLCountry = ds11.Tables[0].Rows[0]["GLCountry"].ToString();
string fff = "select isnull(max(EntSrlNo),0)+1 as EntSrlNo from IDTableExtd where ShowroomCode='" + shrwcode + "' and DocDate='" + RTV_DATE + "'";
SqlDataAdapter das = new SqlDataAdapter(fff, con);
DataSet dss = new DataSet();
das.Fill(dss);
SqlCommand extdcmd = new SqlCommand();
extdcmd.Connection = con;
extdcmd.Transaction = myTrans;
string docpre = "PR" + RTV_DATE.Substring(2, 2);
if (dss.Tables[0].Rows.Count > 0)
{
slno = Convert.ToInt32(dss.Tables[0].Rows[0]["EntSrlNo"].ToString());
extdcmd.CommandText = "insert into IDTableExtd (ShowroomCode,TrnType,TrnCtrlNo,DocNoPrefix,docno,DocDate,EntSrlNo,StockNo,DistributionCenter,GLCountry,GLZone,GLState,GLCity,PartyType,PromoValue_LineLevel,DocQty,NetValue,BatchSrlNo)" +
"values ('" + shrwcode + "'," + "'2300'," + "'" + ddmm + "'," + "'" + docpre + "'," + "'" + ddmm + "'," + "'" + RTV_DATE + "'," + "'" + slno + "'," + "'" + TRN_STOCKNO + "'," + "'" + Dcenter + "'," + "'" + GLCountry + "'," + "'" + GLZone + "',"
+ "'" + GLState + "'," + "'" + GLCity + "','10'," + '0' + ",'" + RTV_QTY + "'," + "'" + RTV_cost + "','0')";
con.Open();
// SqlCommand extdcmd = new SqlCommand(instableextd, con);
extdcmd.ExecuteNonQuery();
con.Close();
}
}
}
myTrans.Commit(); ///Error is getting after exceuting this line..
You need refactor your´s code, first, and use something like that:
using (var = new SqlConnection(_connectionstring))
{
try
{
connection.Open();
using(SqlTransaction transaction = connection.BeginTransaction())
{
using (SqlCommand command1= new SqlCommand(commandtext, connection, transaction ))
{
//Do something here
}
using (SqlCommand command2= new SqlCommand(commandtext, connection, transaction ))
{
//Do another stuff here
}
...
transaction .Commit();
}
}
catch (Exception Ex)
{
if (transaction != null) transaction .Rollback();
}
}
(1)As Joseph said refactor your code using Using statement, which helps to dispose the objects properly.
(2)Your code is prone to SQL Injection, so use SQLParameter.
I've shown a sample from your code make it fully.
con.Open();
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = con;
myCommand.Transaction = myTrans;
myCommand.CommandText = "insert into HSR_Purch_RETURN(PARTNER_ID,RTV_LOCTN) values(#partnerId,#rtv)";
myCommand.Parameters.Add(new SqlParameter("partnerId",PARTNER_ID));
myCommand.Parameters.Add(new SqlParameter("rtv",RTV_LOCTN));
myCommand.ExecuteNonQuery();
//con.Open();
//SqlCommand cmdd = new SqlCommand(insert, con);
//int value1 = cmdd.ExecuteNonQuery();
//values = string.Empty;
con.Close();