I have a code below and it has strange behavior,Line of code after closing of While Loop is not executing. If i write those lines before While loop they got executed. I have searched a lot on this issue but failed.
if ((Convert.ToInt32(newDt.Rows[i]["qty"])) > (Convert.ToInt32(newDt1.Rows[i]["qty"])))
{
k_batch = Convert.ToInt32(newDt.Rows[i]["batch_num"]);
label20.Content = k_batch.ToString();
var dqty = (from row in Addition_result.AsEnumerable() //retriving value from DataTable
where row.Field<int>("batch_num") == k_batch
select row.Field<int>("qty")).FirstOrDefault();
dqty_y = Convert.ToInt32(dqty);
label16.Content = dqty_y.ToString();
con.Open();
SqlCommand cmd1 = new SqlCommand("SELECT quantity,sold_qty,left_qty FROM batch WHERE id='" + k_batch + "'", con);
SqlDataReader batch_qty_details = null;
batch_qty_details = cmd1.ExecuteReader();
while (batch_qty_details.Read())
{
label16.Content = dqty_y.ToString();
batch_qty = Convert.ToInt32(batch_qty_details["quantity"]);
batch_left = Convert.ToInt32(batch_qty_details["left_qty"]);
batch_sold = Convert.ToInt32(batch_qty_details["sold_qty"]);
} //code after this is not executing
label18.Content = batch_left.ToString();
label19.Content = batch_sold.ToString();
label21.Content = dqty_y.ToString();
label22.Content = batch_qty.ToString();
label16.Content = batch_sold + dqty_y;
label17.Content = batch_left - dqty_y;
if (((batch_sold + dqty_y) <= batch_qty) && ((batch_left - dqty_y) >= 0))
{
SqlCommand command = new SqlCommand("update batch set sold_qty=sold_qty+#soldqty2, left_qty=left_qty-#soldqty2 where id=#id2", con);
command.Parameters.AddWithValue("#soldqty2", Convert.ToInt32(dqty_y));
command.Parameters.AddWithValue("#id2", Convert.ToInt32(k_batch));
rexe = command.ExecuteNonQuery();
}
else
{
MessageBox.Show("Please Check you Ordered Quantity !");
}
con.Close();
}
}
Actually there was issue that connection state was already Open and i was trying to open it again. So then i used try-catch block it told me that connection is already open. Now i have changed my code and here it is.
if ((Convert.ToInt32(newDt.Rows[i]["qty"])) > (Convert.ToInt32(newDt1.Rows[i]["qty"])))
{
k_batch = Convert.ToInt32(newDt.Rows[i]["batch_num"]);
label20.Content = k_batch.ToString();
var dqty = (from row in Addition_result.AsEnumerable() //retriving value from DataTable
where row.Field<int>("batch_num") == k_batch
select row.Field<int>("qty")).FirstOrDefault();
dqty_y = Convert.ToInt32(dqty);
label16.Content = dqty_y.ToString();
try
{
//con.Open();
SqlCommand cmd1 = new SqlCommand("SELECT quantity,sold_qty,left_qty FROM batch WHERE id='" + k_batch + "'", con);
SqlDataReader batch_qty_details = null;
batch_qty_details = cmd1.ExecuteReader();
while (batch_qty_details.Read())
{
label16.Content = dqty_y.ToString();
batch_qty = Convert.ToInt32(batch_qty_details["quantity"]);
batch_left = Convert.ToInt32(batch_qty_details["left_qty"]);
batch_sold = Convert.ToInt32(batch_qty_details["sold_qty"]);
}
con.Close();
}
catch(Exception EX)
{
MessageBox.Show(EX.ToString());
}
label18.Content = batch_left.ToString();
label19.Content = batch_sold.ToString();
label21.Content = dqty_y.ToString();
label22.Content = batch_qty.ToString();
label16.Content = batch_sold + dqty_y;
label17.Content = batch_left - dqty_y;
if (((batch_sold + dqty_y) <= batch_qty) && ((batch_left - dqty_y) >= 0))
{
con.Open();
SqlCommand command = new SqlCommand("update batch set sold_qty=sold_qty+#soldqty2, left_qty=left_qty-#soldqty2 where id=#id2", con);
command.Parameters.AddWithValue("#soldqty2", Convert.ToInt32(dqty_y));
command.Parameters.AddWithValue("#id2", Convert.ToInt32(k_batch));
rexe = command.ExecuteNonQuery();
}
else
{
check_qty = -1;
}
}
Related
I Can't do select...
I can not do a select inside a go with dates
recebe uma variavel que determina quantidade de meses a ser calculada MesesDemanda
Calculated a date before and one after
for (int i = 1; i <= MesesDemanda; i++)
{
int cont = 0;
DateTime dataposterior = DateTime.Now, dataanterior = DateTime.Now;
dataanterior = dataanterior.AddMonths(i);
dataposterior = dataposterior.AddMonths(-(i - 1));
con.Open();
cmd = new OleDbCommand("SELECT HistSaida.dataHistSaida, HistSaida.idProdutoHistSaida, HistSaida.qtdHistSaida FROM HistSaida WHERE (((HistSaida.dataHistSaida) BETWEEN #" + dataanterior + "# AND #" + dataposterior + "#) AND idProdutoHistSaida = " + idProduto + ")", con);
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Demanda = Demanda + Convert.ToInt32(dr["qtdHistSaida"]);
cont = 1;
}
}
dr.Close();
con.Close();
Valordivisao = Valordivisao + cont;
}
Use parameters like below
cmd = new OleDbCommand("SELECT dataHistSaida, idProdutoHistSaida, qtdHistSaida FROM HistSaida WHERE ((dataHistSaida <=? AND dataHistSaida >= ?) AND idProdutoHistSaida = ?)", con);
now you can set values like below
cmd.Parameters.AddWithValue("#p1", dataanterior );
cmd.Parameters.AddWithValue("#p2", dataposterior );
cmd.Parameters.AddWithValue("#p3", idProduto );
if you need to take Sum of qtdHistSaida column then you can change the sql statement as below
SELECT SUM(qtdHistSaida) FROM HistSaida WHERE ((dataHistSaida <=? AND dataHistSaida >= ?) AND idProdutoHistSaida = ?)
now you can use ExecuteScalar method to get the sum value as below
var result = cmd.ExecuteScalar();
I have a problem with SqlDataReader.
Here's my code. the problem is when I debug it it doesn't go further than
while(dr.read())
it means the value returned by dr.Read() is false. I don't know what's wrong.
if (CS_time_date[i].Substring(0, 2) == "CS")
{
string cardserial = CS_time_date[i].Substring(4, 5);
try
{
using (SqlConnection con = new SqlConnection(WindowsAppEmp.Properties.Settings.Default.Database1ConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from Card_reg ", con);
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
if ((dr["Cardserial"].ToString() == cardserial))
{
flag = 1;
string EmpID = dr["Id"].ToString();
string F_Name = dr["fname"].ToString();
string L_Name = dr["lname"].ToString();
// Insert_EmpReport(EmpID, F_Name, L_Name, cardserial, CS_time_date,con);
string strsql1 = "Insert into Emp_Report (EmpId,CS,fname,lname,CheckIn,CheckOut,Date,Status) values (#EmpID,#Cs,#fname,#lname,#CheckIn,#CheckOut,#Date,#Status)";
SqlCommand report_cmd = new SqlCommand(strsql1, con);
report_cmd.Parameters.AddWithValue("#EmpID", EmpID);
report_cmd.Parameters.AddWithValue("#Cs", cardserial);
report_cmd.Parameters.AddWithValue("#fname", F_Name);
report_cmd.Parameters.AddWithValue("#lname", L_Name);
if (CS_time_date[i].Substring(9, 10) == "56")
if (CS_time_date[i + 2] == DateTime.Now.ToString("dd/mm/yyyy"))
{
report_cmd.Parameters.AddWithValue("#CheckIn", CS_time_date[i + 1]);
report_cmd.Parameters.AddWithValue("#Status", "Present");
}
else
report_cmd.Parameters.AddWithValue("#Status", "Absent");
else
report_cmd.Parameters.AddWithValue("#CheckOut", CS_time_date[i + 1]);
report_cmd.Parameters.AddWithValue("#Date", CS_time_date[i + 2]);
}
else
flag = 0;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
} while (reader.Peek() != -1);
reader.Close();
It looks like you have the Card_reg table defined in your database but this table doesn't contain any values in it - it is empty. That's why the select * from Card_reg query doesn't return any results and the data reader has nothing to read.
I was trying to remove duplicates from the table Main.
It looks like this(here in csv form):
"Record ID";Status;Placement;Private;Category;Note;Blob
for instance
14341692;132;2147483647;False;4;"29.12.10 14:17";System.Byte[]
Duplicates means, Note is the same. My approach is this:
string strSQL = "SELECT * FROM Main";
OleDbCommand cmd = new OleDbCommand(strSQL, MemoVerbindung);
OleDbDataReader dr = cmd.ExecuteReader();
_items = new List<string>(); // <-- Add this
while (dr.Read())
{
if (dr.FieldCount >= 5)
_items.Add(dr[5].ToString());
}
dr.Close();
progressBar1.Maximum = _items.Count;
for (int a = 0; a < _items.Count; a++)
{
progressBar1.Value = a;
strSQL = "SELECT * FROM Main WHERE Note = '" + _items[a].ToString().Replace("'", "\'") + "'";
cmd = new OleDbCommand(strSQL, MemoVerbindung);
dr = null;
OleDbDataReader dr2 = null;
try
{
dr = cmd.ExecuteReader();
int u = 0;
if (dr.FieldCount > 1)
{
while (dr.Read())
{
if (u >= 1)
{
string was = "DELETE FROM Main WHERE [Record ID] = " + dr[0];
OleDbCommand command = new OleDbCommand(was, MemoVerbindung);
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//MessageBox.Show(reader[0].ToString());
}
reader.Close();
}
u++;
}
}
else
{
while (dr.Read())
{
MessageBox.Show("Übrig");
}
}
dr.Close();
}
catch (Exception mm)
{
//MessageBox.Show(mm.Message);
}
}
MessageBox.Show("Fertig");
progressBar1.Value = 0;
So in the if (u >= 1) section I am trying to leave one version while removing all others. Unfortunately that does not work meaning all entries are removed but the ones raising an error for a reason. What would you change or is there a generally more elegant way?
Use this SQL statement to find the duplicates:
SELECT First(Main.[Note]) AS [NoteField], Count(Main.[Note]) AS NumberOfDups
FROM Main
GROUP BY Main.[Note]
HAVING (((Count(Main.[Note]))>1));
then you can loop through this recordset (grab it as a SnapShot so changes to the underlying data does not change the results)
use !NoteField to know which note to find, and !NumberOfDups to know how many you have to delete (remove this number - 1)
Below 2 links give the preview of my sample application.
http://img812.imageshack.us/i/image1adl.jpg/ : shows mine sample application. All fields are self explanatory (if query, let me know)
http://img834.imageshack.us/i/image2vc.jpg/ : shows, when clicked the "Edit" button from the grid, the timings are shown correctly but the order gets disturbed. (See 7:00 coming on the top and then the timings list are seen).
My Questions
How to correct the timings problem? (Link # 2)
Code for "Edit" is below
protected void lnkEdit_Click(object sender, EventArgs e)
{
int imageid = Convert.ToInt16((sender as Button).CommandArgument);
DataSet ds = new DataSet();
SqlConnection sqlconn = new SqlConnection();
sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["TestConn"].ConnectionString;
string sql = #"SELECT * FROM Images WHERE IsDeleted=0 and Imageid='"+ imageid +"'";
SqlCommand sqlcommand = new SqlCommand(sql, sqlconn);
sqlcommand.CommandType = CommandType.Text;
sqlcommand.CommandText = sql;
SqlDataAdapter da = new SqlDataAdapter(sqlcommand);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
txtImageName.Text = ds.Tables[0].Rows[0].ItemArray[1].ToString();
chkIsActive.Checked = Convert.ToBoolean(ds.Tables[0].Rows[0]["IsActive"].ToString());
ddlStartTime.DataSource = ds;
ddlStartTime.DataTextField = ds.Tables[0].Columns["StartTime"].ColumnName.ToString();
ddlStartTime.DataValueField = ds.Tables[0].Columns["ImageId"].ColumnName.ToString();
ddlStartTime.DataBind();
ddlEndTime.DataSource = ds;
ddlEndTime.DataTextField = ds.Tables[0].Columns["EndTime"].ColumnName.ToString();
ddlEndTime.DataValueField = ds.Tables[0].Columns["ImageId"].ColumnName.ToString();
ddlEndTime.DataBind();
BindDropDownList();
IsEdit = true;
}
When i edit the existing record in the grid, i am getting the values, but the record is not being updated but added as a new record into db. I am aware that i am suppose to write update script. But where to write that?
Below the code is for the same;
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
try
{
string strImageName = txtImageName.Text.ToString();
int IsActive = 1;
if (chkIsActive.Checked)
IsActive = 1;
else
IsActive = 0;
string startDate = ddlStartTime.SelectedItem.Text;
string endDate = ddlEndTime.SelectedItem.Text;
if ( Convert.ToDateTime(endDate) - Convert.ToDateTime(startDate) > new TimeSpan(2, 0, 0) || Convert.ToDateTime(endDate)- Convert.ToDateTime(startDate) < new TimeSpan(2,0,0))
{
//Response.Write(#"<script language='javascript'> alert('Difference between Start Time and End Time is 2 hours'); </script> ");
lblHours.Visible = true;
lblHours.Text = "Difference between Start Time and End Time should be 2 hours";
return;
}
if (checkConflictTime())
{
lblMessage.Visible = true;
lblMessage.Text = "Time Conflict";
return;
}
//if (checkTimeBetween())
//{
//}
if (fuFileUpload.PostedFile != null && fuFileUpload.PostedFile.FileName != "")
{
lblHours.Visible = false;
byte[] imageSize = new Byte[fuFileUpload.PostedFile.ContentLength];
HttpPostedFile uploadedImage = fuFileUpload.PostedFile;
uploadedImage.InputStream.Read(imageSize, 0, (int)fuFileUpload.PostedFile.ContentLength);
SqlConnection sqlconn = new SqlConnection();
sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["TestConn"].ConnectionString;
SqlCommand cmd = new SqlCommand();
if (IsEdit == false)
{
cmd.CommandText = "Insert into Images(FileName,FileContent,IsDeleted,IsActive,StartTime,EndTime) values (#img_name, #img_content,#IsDeleted,#IsActive,#StartTime,#EndTime)";
}
else
{
cmd.CommandText = "Update Images set FileName=#img_name, FileContent=#img_content, IsDeleted= #IsDeleted,IsActive= #IsActive, StartTime=#StartTime,EndTime=#EndTime";
}
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlconn;
SqlParameter ImageName = new SqlParameter("#img_name", SqlDbType.NVarChar, 50);
ImageName.Value = strImageName.ToString();
cmd.Parameters.Add(ImageName);
SqlParameter ActualImage = new SqlParameter("#img_content", SqlDbType.VarBinary);
ActualImage.Value = imageSize;
cmd.Parameters.Add(ActualImage);
SqlParameter DeletedImage = new SqlParameter("#IsDeleted", SqlDbType.Bit);
DeletedImage.Value = 0;
cmd.Parameters.Add(DeletedImage);
SqlParameter IsActiveCheck = new SqlParameter("#IsActive", SqlDbType.Bit);
IsActiveCheck.Value = IsActive;
cmd.Parameters.Add(IsActiveCheck);
SqlParameter StartDate = new SqlParameter("#StartTime", SqlDbType.NVarChar, 100);
StartDate.Value = startDate;
cmd.Parameters.Add(StartDate);
SqlParameter EndDate = new SqlParameter("#EndTime", SqlDbType.NVarChar, 100);
EndDate.Value = endDate;
cmd.Parameters.Add(EndDate);
sqlconn.Open();
int result = cmd.ExecuteNonQuery();
sqlconn.Close();
if (result > 0)
{
lblMessage.Visible = true;
lblMessage.Text = "File Uploaded!";
gvImages.DataBind();
}
}
}
catch (Exception ex)
{
lblMessage.Text = ex.ToString();
}
}
}
Please help!
Where do you define Bool/Bolean IsEdit? I think its value is reset on page postback, that's why it is always false and the record is being inserted. I would suggest you to use a hidden field to track this and set its value there and check the value upon insert/updating. Finally it will be something like...
if (ds.Tables[0].Rows.Count > 0)
{
//your code
hiddenField.Value = "true"; // you can set default value to false
}
and then after
if (hiddenField.Value == "false")
{
cmd.CommandText = "Insert into Images(FileName,FileContent,IsDeleted,IsActive,StartTime,EndTime) values (#img_name, #img_content,#IsDeleted,#IsActive,#StartTime,#EndTime)";
}
else
{
cmd.CommandText = "Update Images set FileName=#img_name, FileContent=#img_content, IsDeleted= #IsDeleted,IsActive= #IsActive, StartTime=#StartTime,EndTime=#EndTime";
}
I have to search the employee details, which is contained within 3 tables. I have used joins in the query query, but it shows error when I press the search button:
sql command not properly ended
c# coding:
try {
//Search Employee Details
Oracle.DataAccess.Client.OracleConnection cn = new Oracle.DataAccess.Client.OracleConnection();
cn.ConnectionString = "user id=system; password=system;";
Oracle.DataAccess.Client.OracleCommand cmd = new Oracle.DataAccess.Client.OracleCommand();
cmd.Connection = cn;
//cn = new Oracle.DataAccess.Client.OracleConnection();
cmd.CommandText = " select deposit.loanid,
form1.empedoj,
form1.empshare,
sharecapital.shareint,
sharecapital.loandt,
sharecapital.loandeduc,
sharecapital.dividend,
sharecapital.sharetot
from form1,
deposit,
sharecapital
where deposit.loanid(+) = sharecapital.loanid = '" + txtlnid.Text.Trim() + "'"; // shows sql command not properly ended
Oracle.DataAccess.Client.OracleDataAdapter ada = new Oracle.DataAccess.Client.OracleDataAdapter(cmd);
System.Data.DataTable dt = new DataTable();
dt.Clear();
ada.Fill(dt);
//Display in Textbox
if (dt.Rows.Count > 0) {
txtlnid.Text = dt.Rows[0].ItemArray[0].ToString();
admdate.Text = dt.Rows[0].ItemArray[1].ToString();
txtadmamt.Text = dt.Rows[0].ItemArray[2].ToString();
txtadmint.Text = dt.Rows[0].ItemArray[3].ToString();
loandt.Text = dt.Rows[0].ItemArray[4].ToString();
txtlnamt.Text = dt.Rows[0].ItemArray[5].ToString();
txtlnint.Text = dt.Rows[0].ItemArray[6].ToString();
txtsctot.Text = dt.Rows[0].ItemArray[7].ToString();
}
if (cn.State == ConnectionState.Closed) {
cn.Open();
}
string str;
str = cmd.ExecuteScalar().ToString();
if (str != null) {
MessageBox.Show("Record Found");
} else {
MessageBox.Show("ID not Match");
}
} catch (Exception ex) {
MessageBox.Show(ex.Message);
}
Your SQL statement becomes
SELECT DEPOSIT.LOANID,
FORM1.EMPEDOJ,
FORM1.EMPSHARE,
SHARECAPITAL.SHAREINT,
SHARECAPITAL.LOANDT,
SHARECAPITAL.LOANDEDUC,
SHARECAPITAL.DIVIDEND,
SHARECAPITAL.SHARETOT
FROM FORM1, DEPOSIT, SHARECAPITAL
WHERE DEPOSIT.LOANID(+) = SHARECAPITAL.LOANID = '" + txtlnid.Text.Trim() + "'";
I suspect it should be:
SELECT DEPOSIT.LOANID,
FORM1.EMPEDOJ,
FORM1.EMPSHARE,
SHARECAPITAL.SHAREINT,
SHARECAPITAL.LOANDT,
SHARECAPITAL.LOANDEDUC,
SHARECAPITAL.DIVIDEND,
SHARECAPITAL.SHARETOT
FROM FORM1, DEPOSIT, SHARECAPITAL
WHERE DEPOSIT.LOANID(+) = SHARECAPITAL.LOANID
AND SHARECAPITAL.LOANID = '" + txtlnid.Text.Trim() + "'";
Also, you have a 3-table join without the correct join conditions, the query is highly likely to return a Cartesian product.
Have you tried putting a semicolon at the end of your query string?
cmd.CommandText = " select deposit.loanid, form1.empedoj, form1.empshare,
sharecapital.shareint, sharecapital.loandt, sharecapital.loandeduc,
sharecapital.dividend, sharecapital.sharetot from form1, deposit ,
sharecapital where deposit.loanid(+) = sharecapital.loanid = '" + txtlnid.Text.Trim() + "';";