code ignored after first button click - c#

This button (loginButton) does everything it's supposed to on the first click. Then, on all subsequent clicks, it refuses change the text of loginStatusLabel at the beginning and end of the method...why? It's as if the code is completely skipped over for with no explanation. The debug messages before and afterword both come through fine, and loginStatusLabel isn't referenced anywhere else.
Am I an idiot?
private void loginButton_Click(object sender, EventArgs e)
{
Debug.Write("Changing label...");
loginStatusLabel.Text = "STATUS: Running..."; //this line is ignored after the first iteration
Debug.WriteLine("label changed.");
loginButton.Enabled = false;
try
{
string LDS01_start = "select count(*) from BBLEARN.AUTH_PROVIDER_LOG where AUTH_PROVIDER_PK1 = 103 ";
string LDAPS_start = "select count(*) from BBLEARN.AUTH_PROVIDER_LOG where AUTH_PROVIDER_PK1 = 106 ";
string middle = "and log_date >= '" + GetDate(loginStartDate) + #"'
and log_date < '" + GetDate(loginEndDate) + #"' ";
string LDS01_0 = LDS01_start + middle + "and event_type = 0";
string LDS01_1 = LDS01_start + middle + "and event_type = 1";
string LDS01_2 = LDS01_start + middle + "and event_type = 2";
string LDS01_5 = LDS01_start + middle + "and event_type = 5";
string LDS01_6 = LDS01_start + middle + "and event_type = 6";
string LDAPS_0 = LDAPS_start + middle + "and event_type = 0";
string LDAPS_1 = LDAPS_start + middle + "and event_type = 1";
string LDAPS_2 = LDAPS_start + middle + "and event_type = 2";
string LDAPS_5 = LDAPS_start + middle + "and event_type = 5";
string LDAPS_6 = LDAPS_start + middle + "and event_type = 6";
GetData(LDS01_0, LDS01_LB0);
GetData(LDS01_1, LDS01_LB1);
GetData(LDS01_2, LDS01_LB2);
GetData(LDS01_5, LDS01_LB5);
GetData(LDS01_6, LDS01_LB6);
GetData(LDAPS_0, LDAPS_LB0);
GetData(LDAPS_1, LDAPS_LB1);
GetData(LDAPS_2, LDAPS_LB2);
GetData(LDAPS_5, LDAPS_LB5);
GetData(LDAPS_6, LDAPS_LB6);
}
catch (Exception exception)
{
Debug.WriteLine(exception);
}
loginButton.Enabled = true;
Debug.Write("Changing label...");
loginStatusLabel.Text = "STATUS: Complete";
Debug.WriteLine("label changed.");
}
private void GetData(string selectCommand, Label label)
{
Debug.WriteLine("Getting data for " + label.Name + "...");
//open the connection
OracleConnection conn = new OracleConnection(connectString);
conn.Open();
Debug.WriteLine("Connection open...");
//define the command
selectCommand = selectCommand.Replace(Environment.NewLine, " ");
OracleDataAdapter dataAdapter = new OracleDataAdapter(selectCommand, conn);
OracleCommandBuilder commandBuilder = new OracleCommandBuilder(dataAdapter);
//run the command
Debug.WriteLine("Running command...");
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
Debug.WriteLine("Command complete.");
//close the connection
conn.Close();
Invoke(new Action(() => RenderData(label, table.Rows[0][0].ToString())));
}
private void RenderData(Label label, string text)
{
label.Text = text;
}

Forgot to create the new thread in the first place. I'm stupid.

Related

After change the query also showing the same data in crystal report

I am showing the data according to the query in crystal report in c#.net desktop application. Problem causing is that when I am change the query, query is changing and according to that query in temp table showing the data also, but in crystal report it is not showing the new data it is showing the same data which is previous after the query change also.
For ex : I want to print bill no 1 so that time okay. But when I want to print bill no 2 at that time also in crystal report showing bill no 1 only. So, that's why I unable to print the bill no 2.
Here is my code in the button click event
private void btn_previewdocument_Click(object sender, EventArgs e)
{
try
{
string mtmptbl = "TmpRetailInvoicePrint";
RetailInvoicePrint frm = new RetailInvoicePrint();
Cursor = Cursors.WaitCursor;
timer1.Enabled = true;
ReportDocument cryRpt = new ReportDocument();
SqlCommand MyCommand = new SqlCommand();
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(cn.ConnectionString);
ConnectionInfo crConnectionInfo = new ConnectionInfo();
TableLogOnInfo crtableLogoninfo = new TableLogOnInfo();
string qryPreviewDocument = " SELECT Client.clientname as ClientName, " + System.Environment.NewLine;
qryPreviewDocument += " RetailInvoice.invoiceno as InvoiceNo, " + System.Environment.NewLine;
qryPreviewDocument += " RetailInvoice.pono as PoNO, RetailInvoice.issuedate as IssueDate, RetailInvoice.duedate as DueDate, " + System.Environment.NewLine;
qryPreviewDocument += " RetailInvoice.discount as Discount, RetailInvoice.shipping as Shipping, RetailInvoice.tax as Tax, RetailInvoice.vat as Vat, " + System.Environment.NewLine;
qryPreviewDocument += " RetailInvoice.sese as Sese, RetailInvoice.paymenttype as PaymentType, RetailInvoice.chequeno as Chequeno, RetailInvoice.totalamt as TotalAmt, " + System.Environment.NewLine;
qryPreviewDocument += " RetailInvoice.description as Description, RetailInvoice.paymentpaid as PaymentPaid, RetailInvoice.subtotal as Subtotal, " + System.Environment.NewLine;
qryPreviewDocument += " RetailInvoicePayment.productid as ProductName, RetailInvoicePayment.uom as Uom, " + System.Environment.NewLine;
qryPreviewDocument += " RetailInvoicePayment.quantity as Quantity, RetailInvoicePayment.price as Price" + System.Environment.NewLine;
qryPreviewDocument += " into " + mtmptbl + " " + System.Environment.NewLine;
qryPreviewDocument += " from tbl_retailinvoice RetailInvoice LEFT OUTER JOIN tbl_retailinvoicepayment RetailInvoicePayment " + System.Environment.NewLine;
qryPreviewDocument += " ON RetailInvoice.invoiceno = RetailInvoicePayment.invoiceno " + System.Environment.NewLine;
qryPreviewDocument += " LEFT OUTER JOIN tbl_clientdetail Client ON RetailInvoice.clientid = Client.clientid " + System.Environment.NewLine;
qryPreviewDocument += " where RetailInvoice.BranchID = " + lbl_branchid.Text + " " + System.Environment.NewLine;
qryPreviewDocument += " and RetailInvoice.YearID = " + lbl_yearid.Text + " " + System.Environment.NewLine;
qryPreviewDocument += " and RetailInvoice.invoiceno = " + txt_invoice.Text + "";
string SQL = "select upper(name) as TABLE_NAME FROM sysobjects WHERE type = 'U' and name = '" + mtmptbl + "' order by name";
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(SQL, cn);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
string qrydrop = "drop table " + mtmptbl + "";
SqlCommand cmd = new SqlCommand(qrydrop, cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
MyCommand = new SqlCommand(qryPreviewDocument, cn);
MyCommand.CommandType = CommandType.Text;
cn.Open();
MyCommand.ExecuteNonQuery();
cn.Close();
string crReportPath = Application.StartupPath.Replace("bin\\Debug", "") + "\\Print";
cryRpt.Load(crReportPath + "\\RptRetailInvoice.rpt");
builder.ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["con"];
string dbName = builder.InitialCatalog;
string dbDataSource = builder.DataSource;
string userID = builder.UserID;
string pass = builder.Password;
crConnectionInfo.ServerName = dbDataSource;
crConnectionInfo.DatabaseName = dbName;
crConnectionInfo.UserID = userID;
crConnectionInfo.Password = pass;
Tables Crtables;
Crtables = cryRpt.Database.Tables;
foreach (CrystalDecisions.CrystalReports.Engine.Table CrTable in Crtables)
{
crtableLogoninfo = CrTable.LogOnInfo;
crtableLogoninfo.ConnectionInfo = crConnectionInfo;
CrTable.ApplyLogOnInfo(crtableLogoninfo);
}
frm.crystalReportViewer1.ReportSource = cryRpt;
frm.crystalReportViewer1.RefreshReport();
Cursor = Cursors.Arrow;
frm.Show();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
So, when any one click the "Preview Document" button at that time "btn_previewdocument_Click" event occur.
And I want to do that in this event according to the query data want to display in crystal report.
Advance in thanks.
Try this. Before frm.crystalReportViewer1.ReportSource = cryRpt; add cryRpt.Refresh();

I want to edit the datagridview to Update Dataset directly to DB,but always failed

My Problem as follows;
Last row of datagridview is always Focused, so when I click the btnSave of toolStripButton, I can not save the last row data to the database. How should I solve this problem? I know if I use the Button Control, I can solve this problem. But I want to know more:
private void btnSave_Click(object sender, EventArgs e)
{
dgvHead.EndEdit();
dgvHead.RefreshEdit();
dgvHead.Refresh();
dgvHead.Update();
dgvHead.LostFocus += new EventHandler(dataGridView1_LostFocus);
//dgvHead.ClearSelection();
//int id = 0;
//保存到数据库之前先判断一下主表是否有重复记录
string fno = txtfNo.Text.Trim();
string fname = txtPname.Text.Trim();
int orderqty = Convert.ToInt32(txtOrderQty.Text);
double orderc = Convert.ToDouble(txtOrderCoefficient.Text);
Image pic = pbchef.Image;
//主表的修改
string sql1 = "select count(1) from desProductAttach where fno='" + fno + "' and fno!='" + args["pNo"].ToString() + "' and fname='" + fname + "' and orderqty=" + orderqty + " and orderCoefficient=" + orderc + "";
int count = Convert.ToInt32(SqlHelp.GetValue(CommandType.Text, sql1));
if (count != 0)
{
MessageBox.Show("数据库中已经存在重复记录,请修改后重新录入!");
return;
}
string sql2 = #"update desProductAttach set fno='" + fno + "',fname='" + fname + "',orderqty=" + orderqty + ",orderCoefficient=" + orderc + " where id="+id+"";
SqlHelp.ExecuteNonQuery(CommandType.Text,sql2);
//子表的更新(通过数据源更新)
if (ds1.HasChanges())
{
SqlCommandBuilder cb = new SqlCommandBuilder(sda1);
sda1.Update(ds1.Tables[0]);
ds1.AcceptChanges();
// dgvHead.Update();
MessageBox.Show("保存成功");
// ischange = false;
}
}

Datareader Exception Thrown Database - DateTime

In my Access database I have an AutditLog table which Looks like this
I simply want to access this table and display each bit of information when Created*(which is the date of the logs) is equal to today's date.
this is my code
private void ITemail()
{
string FinEmail;
clsDBConnector dbConnector = new clsDBConnector();
OleDbDataReader dr;
dbConnector.Connect();
var sqlStr = " SELECT Created, [Action], ConnectionLoc, ConnectionSystem, Resource, [Text], RecordId, ToVal, ClientName"
+ "FROM tblAudit WHERE (ClientName = '" + Client + "') AND 'Created' = '" + ToDate() + "'";
dr = dbConnector.DoSQL(sqlStr);
while (dr.Read())
{
txtIT.Text = dr[0].ToString() + dr[1].ToString() + dr[2].ToString() + dr[3].ToString() + dr[4].ToString() + dr[5].ToString() + dr[6].ToString()
+ dr[7].ToString() + dr[8].ToString();
}
}
private string ToDate()
{
return DateTime.Today.ToString("dd/MM/yyyy");
}
the problem is that nothing is returned even when i try in server explorer with the correct date as a string nothing is returned. When it reaches the While loop this exception is thrown:
Any help would be very much appreciated
Your date format and the date delimiter is incorrect and spaces are missing:
private void ITemail()
{
string FinEmail;
clsDBConnector dbConnector = new clsDBConnector();
OleDbDataReader dr;
dbConnector.Connect();
var sqlStr = "SELECT Created, [Action], ConnectionLoc, ConnectionSystem, Resource, [Text], RecordId, ToVal, ClientName "
+ "FROM tblAudit WHERE (ClientName = '" + Client + "') AND Created = #" + ToDate() + "#";
dr = dbConnector.DoSQL(sqlStr);
while (dr.Read())
{
txtIT.Text = dr[0].ToString() + dr[1].ToString() + dr[2].ToString() + dr[3].ToString() + dr[4].ToString() + dr[5].ToString() + dr[6].ToString()
+ dr[7].ToString() + dr[8].ToString();
}
}
private string ToDate()
{
return DateTime.Today.ToString("yyyy'/'MM'/'dd");
}

Issues with Repeater going through each item

I am having issues with looping through my repeater to save all the data. If I have 30 items in the repeater it will go through the repeater 30 times. However the ID never is updated. I set the id to textbox so I know the value is correct with DB and not duplicated.
Here i the code.
protected void Save()
{
foreach (RepeaterItem RI in Repeater1.Items)
{
bool budgetvalue = CBBudgeted.Checked;
//lblHeader.Text = rs["BudgetYear"].ToString();
string Janbudget = txtJanBudget.Text;
string Febbudget = txtFebBudget.Text;
string Marbudget = txtMarBudget.Text;
string Aprbudget = txtAprBudget.Text;
string Maybudget = txtMayBudget.Text;
string Junbudget = txtJunBudget.Text;
string Julbudget = txtJulBudget.Text;
string Augbudget = txtAugBudget.Text;
string Sepbudget = txtSepBudget.Text;
string Octbudget = txtOctBudget.Text;
string Novbudget = txtNovBudget.Text;
string Decbudget = txtDecBudget.Text;
string PriceEach = txtPriceEach.Text;
string IDnum = txtID.Text;
string saveStaff = "Update sales_budget " +
"set Janbudget " + Janbudget +
", Febbudget " + Febbudget +
", Marbudget " + Marbudget +
", Aprbudget " + Aprbudget +
", Maybudget " + Maybudget +
", Junbudget " + Junbudget +
", Julbudget " + Julbudget +
", Augbudget " + Augbudget +
", Sepbudget " + Sepbudget +
", Octbudget " + Octbudget +
", Novbudget " + Novbudget +
", Decbudget " + Decbudget +
", Budget " + budgetvalue +
", Price_Each " + PriceEach +
" Where id = " + IDnum;
GetConnection Sales = new GetConnection();
string conn = Sales.SalesConnect;
SqlCommand querySaveStaff = new SqlCommand(saveStaff);
using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(conn))
{
System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(saveStaff, con);
con.Open();
try
{
command.ExecuteNonQuery();
}
catch
{
//GetConnection Sales = new GetConnection();
// string conn = Sales.SalesConnect;
// using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(conn))
// {
// System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(mysql, con);
// con.Open();
// System.Data.SqlClient.SqlDataReader rs = command.ExecuteReader();
// while (rs.Read())
}
con.Close();
}
}

SqlDataReader returns x rows but SQL query returns y rows

First time post as I'm a bit stuck here.
I am using this code to return some rows from a SQL Server database:
public static SqlDataReader SQLSelect(string sqlcommand, string[,] parameters, int length)
{
try
{
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
conn.Open();
SqlDataReader reader;
SqlCommand cmd = new SqlCommand(sqlcommand, conn);
var allLength = parameters.Length;
for (int i = 0; i < parameters.Length - length; i++)
{
string paramid = parameters[i, 0];
if (paramid == "#date" || paramid == "#Date" || paramid == "#DATE")
{
string paramvalue = parameters[i, 1];
DateTime date = Convert.ToDateTime(paramvalue);
paramvalue = date.ToString("yyyy-MM-dd HH':'mm':'ss");
cmd.Parameters.Add(new SqlParameter(paramid, paramvalue));
}
else
{
string paramvalue = parameters[i, 1];
cmd.Parameters.Add(new SqlParameter(paramid, paramvalue));
}
}
cmd.CommandType = CommandType.StoredProcedure;
reader = cmd.ExecuteReader();
return reader;
}
catch
{
return null;
}
}
This function is called like so
string[,] parameters = new string[1, 2] { { "#studentid", studentid } };
SqlDataReader reader = Common.SQLSelect(Common.tblstudentprogressselectforprinting, parameters, 1);
now all runs fine except the reader only contains 13 rows of data where as the actual query being
exec sp_tblstudentprogress_selectforprinting #studentid=N'87'
as an example, returns 91 rows.
I'm at a loss as to why this is the case. Only thing I have noticed is when using SQL Server profiler, running the query from SQL Server, there is a RPC: Started and Completed, as for running from withing my web app, there is only an RPC: Started.
Any thoughts on this?
EDIT:
here is how I enumerate the reader
protected void btnPrint_Click(object sender, EventArgs e)
{
string[,] parameters = new string[1, 2] { { "#studentid", studentid } };
SqlDataReader reader = Common.SQLSelect(Common.tblstudentprogressselectforprinting, parameters, 1);
string firstname = txtFirstName.Text;
string lastname = txtLastName.Text;
int i=0;
string[] heading1 = new string[reader.FieldCount];
string[] heading2 = new string[reader.FieldCount];
string[] log = new string[reader.FieldCount];
try
{
while (reader.Read())
{
heading1[i] = "Progress Log for: Block: " + reader["block"].ToString() + " Lesson: " + reader["lesson"].ToString();
heading2[i] = "";
log[i] =
/*"PROGRESS LOG for " + reader["firstname"].ToString() + " " + reader["lastname"].ToString() + " Printed on " + DateTime.Today.ToShortDateString() + Environment.NewLine +*/
Environment.NewLine +
"Teacher: " + reader["teacher"].ToString() + Environment.NewLine +
"Date: " + reader["date"].ToString() + Environment.NewLine +
"Year: " + reader["year"].ToString() + Environment.NewLine +
"Block: " + reader["block"].ToString() + Environment.NewLine +
"Lesson: " + reader["lesson"].ToString() + Environment.NewLine +
"Warm Up: " + reader["warmup"].ToString() + Environment.NewLine +
"Range: " + reader["range"].ToString() + Environment.NewLine +
"Technique Sheet: " + reader["techniquesheet"].ToString() + Environment.NewLine +
"Technique Other: " + reader["techniqueother"].ToString() + Environment.NewLine +
Environment.NewLine +
"Notes: " + reader["notes"].ToString() + Environment.NewLine +
Environment.NewLine +
"Mark: " + reader["mark"].ToString()+ Environment.NewLine ;
i++;
}
}
catch
{
}
finally
{
if (Common.conn != null)
{
Common.conn.Close();
}
}
Common.PDFCreateProgressLog("Progress log for: " + firstname + " " + lastname, "Progress log for: " + firstname + " " + lastname, "PDF_" + firstname + " " + lastname + "-" + DateTime.Today.ToString("yyyy-MM-dd") + ".pdf", "Progress log for: " + firstname + " " + lastname, log, heading1, heading2);
}
You are confusing the meaning of the FieldCount property. It identifies the number of Columns, not the number of Rows. You cannot determine the total number of rows from a streaming source like a Reader, without enumerating all of the rows first (at least once, anyway).
So you will need to extend your arrays each time (lists might be easier for this) you read a row from the Reader and test the Reader to se when there are no more rows.

Categories

Resources