I have 8 tabs containing number of records in each one and a function that should count the number of records in each tab and put it in the tab’s header name like the following:
public void count_records(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Test"].ConnectionString);
string[] commands = {
"SELECT * FROM myTable",
"SELECT * FROM myTable WHERE Status=2",
"SELECT * FROM myTable WHERE Status=3",
"SELECT * FROM myTable WHERE Status=8",
"SELECT * FROM myTable WHERE Status=4",
"SELECT * FROM myTable WHERE Status=7",
"SELECT * FROM myTable WHERE Status=1",
"SELECT * FROM myTable WHERE Status=5"
};
int[] LLCount = new int[commands.Length];
try
{
for (int i = 0; i < commands.Length; i++)
{
SqlCommand cmd = new SqlCommand(commands[i], con);
SqlDataReader reader;
int count = 0;
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
count++;
}
LLCount[i] = count;
myTab1.HeaderText += " (" + LLCount[0] + ")";
myTab2.HeaderText += " (" + LLCount[1] + ")";
myTab3.HeaderText += " (" + LLCount[2] + ")";
myTab4.HeaderText += " (" + LLCount[3] + ")";
myTab5.HeaderText += " (" + LLCount[4] + ")";
myTab6.HeaderText += " (" + LLCount[5] + ")";
myTab7.HeaderText += " (" + LLCount[6] + ")";
myTab8.HeaderText += " (" + LLCount[7] + ")";
}
}
catch (Exception ex) { string ee = ex.Message; }
finally { con.Close(); }
}
Now, the problem I’m facing is that the reader gets the number of records of the first command string correctly "LLCount[0]" but the rest of them are zeros.
EDIT:
I added reader.Close(); and moved the assignment outside the loop but
it didn't even show the zeros or anything as before. So, I think it
dosen't matter whether you put reader.Close(); or not.
Look for //* in the code to find the differences. The main chnage was that I put con.Open(); before the for loop. Opening the same connection again is throwing error when the connection is not closed. this error was getting caught in catch block,
public void count_records(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Test"].ConnectionString);
//*** See Count(*) in the sql
string[] commands = {
"SELECT count(*) FROM myTable",
"SELECT count(*) FROM myTable WHERE Status=2",
"SELECT count(*) FROM myTable WHERE Status=3",
"SELECT count(*) FROM myTable WHERE Status=8",
"SELECT count(*) FROM myTable WHERE Status=4",
"SELECT count(*) FROM myTable WHERE Status=7",
"SELECT count(*) FROM myTable WHERE Status=1",
"SELECT count(*) FROM myTable WHERE Status=5"
};
int[] LLCount = new int[commands.Length];
try
{
//*****This is the change I made
con.Open();
for (int i = 0; i < commands.Length; i++)
{
SqlCommand cmd = new SqlCommand(commands[i], con);
int count = 0;
//*** Se the use of ExecuteScalar
count =Convert.ToInt32( cmd.ExecuteScalar());
LLCount[i] = count;
}
//***Now Assign the Tab Headers
}
catch (Exception ex) { string ee = ex.Message; }
finally { con.Close(); }
}
}
Related
I have a form that users will fill out and when they submit, all data is pushed to a database.
My Problem is that I have a CheckBoxList and if a user selects multiple checkboxes it only inputs the first item into the database. How do I make it so that all the items are inputted into the same row and separated by commas.
Here is my current code:
protected void Button1_Click(object sender, EventArgs e)
{
//Start Code
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = conString + txtFirst.Text + "','" + txtLast.Text +
"','" + txtEmail.Text + "','" + lstBranch.Text + "','" + lstAccess.Text + "')";
cmd.ExecuteNonQuery();
con.Close();
}
You can loop the items like this
string result = string.Empty;
for (int i = 0; i < checkboxlist1.Items.Count; i++)
{
if (checkboxlist1.Items[i].Selected)
{
result += checkboxlist1.Items[i].Text + ", ";
}
}
// remove the final comma.
// add 'result' to your sql stmt.
So what I'm trying to do is once I click a button. I want one sql query to insert values to the "Return_Process" Table and another sql query to delete data from the matching loan ID in another table, which is "Loan_Process".
This is the code I have written but its not deleting anything, its inserting the values to the return process but not deleting it from the loan process.
//Global variable declaration
string path;
string sql;
string sql2;
//create a method for database connection
public void connection()
{
//connection string
path = #"Data Source=NATHAN-PC\SQLEXPRESS;Initial Catalog=ASP;Integrated Security=True";
}
protected void Button1_Click(object sender, EventArgs e)
{
{
connection();
SqlConnection con = new SqlConnection(path);
con.Open();
//try
{
sql = "INSERT INTO Return_Process (Return_ID, FIne, Actual_Returned_Date, Loan_ID) VALUES ('" + txtRID.Text + "','" + txtfine.Text + "','" + TextBox1.Text + "','" + txtLID.Text + "')";
sql2 = "Delete FROM Loan_Process WHERE Loan_ID='"+txtLID+"'";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
//lblerrormsg.Visible = true;
//lblerrormsg.Text = "Success";
con.Close();
//GridView1.DataBind();
}
//catch (SqlException)
//{
// //lblerrormsg.Visible = true;
// //lblerrormsg.Text = "Invalid";
//}
con.Close();
//GridView1.DataBind();
}
}
}
}
I'm pretty bad at ASP.net, so if someone could tell me what to do to execute both queries at the same time, would greatly appreciate it.
Do something like this:
//your code
sql = "INSERT INTO Return_Process (Return_ID, FIne, Actual_Returned_Date, Loan_ID)"
+ " VALUES (#rid, #fine, #retDate, #lid); " //note ; inside
+ "Delete FROM Loan_Process WHERE Loan_ID=#lid;";
var cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#rid", SqlDbType.Int).Value = Int.Parse(txtRID.Text);
//similar for 3 remaining parameters. Just set correct SqlDbType
con.Open();
cmd.ExecuteNonQuery();
con.Close();
I have a sqlite db file. I am using DB Browser for Sqlite as the client. I went in and ran delete from command on most of my tables. Thereafter I tried to export using the option Database to SQL file I notice all my data is appearing in it. What I wondering is that why the data have not been deleted? I know the sqlite file size will not shrink.
Below is snippet of my codes.
string str = #"Data Source=" + userFilePath + "\\mysqlite.sqlite3";
using (SQLiteConnection con = new SQLiteConnection(str))
{
con.Open();
SQLiteTransaction trans = con.BeginTransaction();
try
{
String cmdSelect1 = "Select * from table1 where companyID='" + companyID + "' And month='" + month + "' And year='" + year + "'";
int fiscalPeriod = Convert.ToInt32(monthNumber);
int financialYear = Convert.ToInt32(itemvalueyear);
using (SQLiteCommand cmd1 = new SQLiteCommand(cmdSelect1, con, trans))
{
SQLiteDataReader dr1 = cmd1.ExecuteReader();
if (dr1.Read())
{
MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show("Records Already Exist ? Are you confirm replace it?", "Delete Confirmation", System.Windows.MessageBoxButton.YesNo);
if (messageBoxResult == MessageBoxResult.Yes)
{
String deleteTable = "Delete from table1 where companyID='" + companyID + "' And month='" + month + "' And year='" + year + "'";
using (SQLiteCommand cmdDeleteTb1 = new SQLiteCommand(deleteTable, con, trans))
{
cmdDeleteTb1.ExecuteNonQuery();
cmdDeleteTb1.Dispose();
}
foreach (object line in linesC)
{
if (line.GetType() == typeof(TypeC))
{
String cmdText2 = "INSERT INTO table1(tbID,companyID,month,year) VALUES(#tbID,#companyID,#month,#year)";
using (SQLiteCommand cmd = new SQLiteCommand(cmdText2, con, trans))
{
cmd.Parameters.AddWithValue("#tbID", tbID);
cmd.Parameters.AddWithValue("#companyID", companyID);
cmd.Parameters.AddWithValue("#month", month);
cmd.Parameters.AddWithValue("#year", year);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.Dispose();
}
}
}
}
}
dr1.Close();
cmd1.Dispose();
}
trans.Commit();
MessageBox.Show("Successfully Inserted Into Database");
}
catch (Exception ex)
{
MessageBox.Show("Rollback " + ex.ToString());
trans.Rollback();
}
con.Close();
con.Dispose();
GC.Collect();
Ok:
It appears you are beginning two transactions. You begin your loop inserts after you begin your delete.
Commit your Delete transaction and then later commit your inserts.
This is than committing after beginning both transactions.
I'm trying to duplicate a record in my database and I used this code you see below, the sql query worked perfectly in sql server but here I don't know what the problem...help me please
//Insert new Order
int newOrderId = 0;
if (e.CommandName == "Repeat")
{
try
{
SqlConnection con = DataAccess.Connection.GetDBConnection();
//duplicate the jobs from the old order to the new added order
sqlCmd.Parameters.Clear();
string com2 = "Insert Into [OrderItems] (orderId, productId, quantity, [length], note, multipleSlip, internalDiameter, " +
"wall, machineReCuttingId,winderId, jobNote) (select #newOrderId, productId, quantity, [length], note, multipleSlip, " +
"internalDiameter, wall, machineReCuttingId, winderId, jobNote FROM OrderItems Where orderId=#oldOrderId)";
SqlCommand sqlCmd = new SqlCommand(com2, con);
sqlCmd.Parameters.Add("#newOrderId", SqlDbType.Int).Value = newOrderId;
//assign the old order Id to the insert parameter #oldOrderId
sqlCmd.Parameters.Add("#oldOrderId", SqlDbType.Int).Value = Convert.ToInt32(e.CommandArgument);
sqlCmd.ExecuteNonQuery();
StatusLabel.Text = "The New Order is" + newOrderId.ToString() + " The Old order ID is: " + e.CommandArgument.ToString();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
OrderGridView.DataSource = ViewDataSource(selectCustomer);
OrderGridView.DataBind();
// Response.Redirect("../Orders/AddNewOrder.aspx?customerId=" + selectCustomer + "&" + "orderId=" + newOrderId);
}
By the way I tested the values of newOrderId and the oldOrderId they are both correct
I want to update multi checkboxlist value to the the database. I already databound my checkboxlist from other table which is the medicine table. Now i want to update my value to consultation table, but i can not
`
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
for (int i = 0; i < txtcheckbox.Items.Count - 1; i++)
{
if (txtcheckbox.Items[i].Selected == true)
{
str = str + txtcheckbox.Items[i].Text + ",";
}
}
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
String sql = "UPDATE [consultation] set mname3 = " + str + " WHERE [conid] = #conid";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#conid", txtconid);
cmd.Parameters.AddWithValue("#mname3", str);
int j = cmd.ExecuteNonQuery();
if (j > 0)
{
Label2.Visible = true;
Label2.Text = "Successfully Complete Dispensary";
txtconid.Text = "";
}
else
{
Label2.Visible = true;
Label2.Text = "Not Successfully Complete Dispensary";
txtconid.Text = "";
}
con.Close();
}
catch
{
Label2.Visible = true;
Label2.Text = "Error";
txtconid.Text = "";
}
}
`
I guess you have exception here. Because:
String sql = "UPDATE [consultation] set mname3 = " + str + " WHERE [conid] = #conid";
here you use concatenation of strings and your sql query will look like:
UPDATE [consultation] set mname3 = sometextvale WHERE [conid] = #conid
mname3 have nvarchar sql type I guess, so you need to put string value in qoutes:
String sql = "UPDATE [consultation] set mname3 = ' " + str + " ' WHERE [conid] = #conid";
Or you can use paramaeter for sql query, like you already did for #conid:
String sql = "UPDATE [consultation] set mname3 = #mname3 WHERE [conid] = #conid";
It's better solution in security way.
Some additional comments:
for (int i = 0; i < txtcheckbox.Items.Count - 1; i++)
Are you sure here should be txtcheckbox.Items.Count - 1? You will lost the last one.
And the 2nd one: Mix code for construction and execution query (DAL) in code behind of page with some kind of business logic not a good practice =)