Removing character after retrieving from database - c#

I would like to remove first two chatracter of a string but it is not working. Can i know why was this issue
while (rdr.Read())
{
if (rdr.HasRows)
{
sqlNew = sqlNew + "', '" + rdr.GetString(0);
}
else
{
break;
}
}
if (!(sqlNew == ""))
{
sqlNew = sqlNew + "'";
sqlNew.Substring(2);
}
textBox1.Text = sqlNew;

Substring doesn't modify the string (since strings are immutable), it returns a new string with the result, so:
sqlNew = sqlNew.Substring(2);

Related

Inserting Multiple selected Listbox items into the same cell in SQL table

I want to insert multiple list box items into a a cell In SQL table with a comma dividing the items. The code posted below will only add the first selected item within a listbox. Hence If you select 2 or 10 items the first one u selected will be Inserted into the table. The for loop is my problem, I need to get all the selected values.
Thanks
protected void pg_upload_Click(object sender, EventArgs e)
{
using (SqlConnection mycon = new SqlConnection(connectionstring))
{
using (SqlCommand mycmd = mycon.CreateCommand())
{
if (textbox_make.Text == string.Empty || textbox_number.Text == string.Empty)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('The Make/Model and Number must be Entered')", true);
}
else
{
string str = "";
for (int i=0; i<= listbox_software.Items.Count; i++)
{
str = listbox_software.SelectedItem.ToString();
}
mycon.Open();
mycmd.CommandText = "INSERT INTO tbl_PG (Model, PGNumber, AssetNo, Area, Owner,IPAddress, SerialNo, OSVersion, Memory, Software) " +
"Values ('" + textbox_make.Text + "' , '" + textbox_number.Text + "' , '" + textbox_asset.Text + "' , '" + drop_area.Text + "' , '" + drop_owner.Text + "' , '" + textbox_ip.Text + "' " +
", '" + textbox_serial.Text + "' , '" + textbox_os.Text + "' , '" + textbox_memory.Text + "' , '" + str + "')";
mycmd.ExecuteNonQuery();
PopulateGridView();
lblsuscessmessage.Text = "Selected Record Added";
lblerrormessage.Text = "";
textbox_make.Text = string.Empty;
textbox_number.Text = string.Empty;
textbox_asset.Text = string.Empty;
textbox_ip.Text = string.Empty;
textbox_serial.Text = string.Empty;
textbox_os.Text = string.Empty;
textbox_memory.Text = string.Empty;
}
}
}
}
Add following namespace:
using System.Linq;
Create a string array of selected items and then use string.join:
var selection = listbox_software.SelectedItems
.Cast<string>()
.ToArray();
var str = string.Join(",", selection);
I found out the answer.
// To access checkbox list item's value //
string total = "";
foreach (ListItem listItem in listbox_software.Items)
{
if (listItem.Selected)
{
total = total + "[" + listItem.Value + "][ " + " ";
}
}
string str = total.ToString();

C# IF statement for a checkbox Value Points wont register into DB

I need help for my If Statement, at first it registers into the DB but only the value of 8, even if multiple values are tick. I know my if statements are wrong, but i have no idea what else to do. So should I remove the use another way if it's possible or I just messed a code up? I'm really bad at If's statement.
String points = null;
String ServiceCarWash = "Not Booked";
String ServiceCarPolish = "Not Booked";
String ServiceCarWax = "Not Booked";
int CustomerID = 0;
private void btnBook_Click_1(object sender, EventArgs e)
{
try
{
connection.Open();
String query = "INSERT into Booking ([Time],[Date],[CID],[VehicleNumber],[CarWash],[CarPolish],[CarWax]) VALUES('" + cmbTime.Text + "','" + dateTimePicker1.Text + "','" + CustomerID + "','" + txtVn.Text + "','" + ServiceCarWash + "','" + ServiceCarPolish + "','" + ServiceCarWax + "')";
OleDbCommand command = new OleDbCommand(query);
command.Connection = connection;
command.ExecuteNonQuery();
if (CbCarwash.Checked)
{
ServiceCarWash = "Booked";
}
if (CbCarPolish.Checked)
{
ServiceCarPolish = "Booked";
}
if (CbCarWax.Checked)
{
ServiceCarWax = "Booked";
}
{
if (txtMember.Text.Equals("VIP"))
{
if (ServiceCarPolish == "Booked")
{
points = "20";
}
if (ServiceCarWash == "Booked")
{
points = "2";
}
if (ServiceCarWax == "Booked")
{
points = "8";
}
}
else if (txtMember.Text.Equals("Walk-In"))
{
if (ServiceCarPolish == "Booked")
{
points = "0";
}
if (ServiceCarWash == "Booked")
{
points = "0";
}
if (ServiceCarWax == "Booked")
{
points = "0";
}
}
string query1 = "UPDATE *Customer set Points='" + points + "'";
OleDbCommand command1 = new OleDbCommand(query1);
command1.Connection = connection;
command1.ExecuteNonQuery();
MessageBox.Show("Your time has been booked.");
connection.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
How to accumulate points in code as per comments on previous question. See comments in the below and look out for the += signs.
//String points = null;
int points = 0;
String ServiceCarWash = "Not Booked";
String ServiceCarPolish = "Not Booked";
String ServiceCarWax = "Not Booked";
int CustomerID = 0;
private void btnBook_Click_1(object sender, EventArgs e)
{
try
{
connection.Open();
String query = "INSERT into Booking ([Time],[Date],[CID],[VehicleNumber],[CarWash],[CarPolish],[CarWax]) VALUES('" + cmbTime.Text + "','" + dateTimePicker1.Text + "','" + CustomerID + "','" + txtVn.Text + "','" + ServiceCarWash + "','" + ServiceCarPolish + "','" + ServiceCarWax + "')";
OleDbCommand command = new OleDbCommand(query);
command.Connection = connection;
command.ExecuteNonQuery();
if (CbCarwash.Checked)
{
ServiceCarWash = "Booked";
}
if (CbCarPolish.Checked)
{
ServiceCarPolish = "Booked";
}
if (CbCarWax.Checked)
{
ServiceCarWax = "Booked";
}
{
if (txtMember.Text.Equals("VIP"))
{
if (ServiceCarPolish == "Booked")
{
points += 20;
}
if (ServiceCarWash == "Booked")
{
points += 2;
}
if (ServiceCarWax == "Booked")
{
points += 8;
}
}
else if (txtMember.Text.Equals("Walk-In"))
{
if (ServiceCarPolish == "Booked")
{
points += 0;
}
if (ServiceCarWash == "Booked")
{
points += 0;
}
if (ServiceCarWax == "Booked")
{
points += 0;
}
}
//string query1 = "UPDATE *Customer set Points='" + points + "'";
string query1 = "UPDATE *Customer set Points='" + points.ToString() + "'";
OleDbCommand command1 = new OleDbCommand(query1);
command1.Connection = connection;
command1.ExecuteNonQuery();
MessageBox.Show("Your time has been booked.");
connection.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
Set your fields before inserting in to the database.
Move this code to the end of the method (or to just before the Customer update):
connection.Open();
String query = "INSERT into Booking ([Time],[Date],[CID],[VehicleNumber],[CarWash],[CarPolish],[CarWax]) VALUES('" + cmbTime.Text + "','" + dateTimePicker1.Text + "','" + CustomerID + "','" + txtVn.Text + "','" + ServiceCarWash + "','" + ServiceCarPolish + "','" + ServiceCarWax + "')";
OleDbCommand command = new OleDbCommand(query);
command.Connection = connection;
command.ExecuteNonQuery();
Also, is *Customer the right table name, should it not just be Customer?
Check the value of your checkboxes to see if they are coming through correctly, then step through your IF's to make sure they calculate correctly. Refactoring in to smaller methods may help you break down the problem so that it is less complex and easier to work with.
Also check your brackets - you have some crazy stuff going on. See the second to last bracket below and you also have something weird going on a bit higher up with a bracket the wrong way around.
else if (txtMember.Text.Equals("Walk-In"))
{
if (ServiceCarPolish == "Booked")
{
points = "0";
}
if (ServiceCarWash == "Booked")
{
points = "0";
}
if (ServiceCarWax == "Booked")
{
points = "0";
}
**{**
}
Also make sure txtMember.Text always has a value so that points are set. Depending on your input, you can make your code a bit more robust by comparing tolower() in strings, e.g.: txtMember.Text.ToLower().Equals("walk-in").
And step through with the debugger! :)

SqlCommand AddWithValue and if statements issue with gridview

I am trying to build a web form that uses SQL queries to help populate various dropdowns and display results in gridviews, the issue i'm having at the moment is getting the user input to replace varibles in the SQL query.
My query is as follows:
SELECT TOP 50
'Select' AS 'Select',
id_ref AS 'Number',
created_date AS 'Date Created',
address 'Address',
category AS 'Category',
borough
FROM Events
WHERE location_address LIKE '%%'
AND borough #borcond
AND admin_ref #stacond
AND id_ref #Numcond
AND category #cat
AND created_date #startDate
AND created_date #endDate
AND address LIKE #Addresscond
ORDER BY id_todays_date DESC
My C# code is as follows:
public void SQLQueryv2(
string AddressSel,
string startDateSel,
string endDateSel,
string incidentSel,
string borsel,
string stasel,
string numsel)
{
//this is filled in really
SqlConnection Connection = new SqlConnection(
"Data Source=;Initial Catalog=;User=;Password=;");
string sqlquery = <<as above>>
try
{
SqlCommand Command = new SqlCommand(sqlquery, Connection);
Connection.Open();
if (borsel == "Select Borough")
{
Command.Parameters.AddWithValue("#borcond", " = IS NOT NULL ");
}
else
{
Command.Parameters.AddWithValue("#borcond","= " + "'" + borsel + "'");
}
if (stasel == "Select Town")
{
Command.Parameters.AddWithValue("#stacond", " = IS NOT NULL ");
}
else
{
Command.Parameters.AddWithValue("#borcond","= "+ "'" + borsel + "'");
}
if (startDateSel == "")
{
Command.Parameters.AddWithValue("#startDate", " = IS NOT NULL");
}
else
{
Command.Parameters.AddWithValue(
"#startDate",
">= CONVERT(datetime," + "'" + startDateSel + "'" + ",103)");
}
if (endDateSel == "")
{
Command.Parameters.AddWithValue("#endDate", " = IS NOT NULL");
}
else
{
Command.Parameters.AddWithValue(
"#endDate",
">= CONVERT(datetime," + "'" + endDateSel + "'" + ",103)");
}
if (incidentSel == "Select Category")
{
Command.Parameters.AddWithValue(
"#cat",
" in ('cat a','cat b','cat c')");
}
else
{
Command.Parameters.AddWithValue(
"#cat",
" AND category =" + "'" + incidentSel + "'");
}
if (AddressSel == "")
{
Command.Parameters.AddWithValue("#Addresscond", "%%");
}
else
{
Command.Parameters.AddWithValue("#Addresscond","%" + AddressSel + "%");
}
if (numsel == "")
{
Command.Parameters.AddWithValue("#Numcond", " = IS NOT NULL ");
}
else
{
Command.Parameters.AddWithValue("#Numcond", "= " + "'" + numsel + "'");
}
//use adapter to populate dataset...
SqlDataAdapter DataAdapter = new SqlDataAdapter(sqlquery, Connection);
DataTable DataTable = new DataTable();
DataAdapter.SelectCommand = Command;
DataAdapter.Fill(DataTable);
//then bind dataset to the gridview
GridView1.AutoGenerateColumns = true;
GridView1.DataSource = DataTable;
GridView1.DataBind();
lblResults.Visible = true;
lblResults.ForeColor = System.Drawing.Color.Green;
lblResults.Text = "Your search has returned "
+ Dataset.Tables[0].Select(
"'Incident Number' IS NOT NULL").Length.ToString()
+ " records.";
}
catch (Exception err)
{
lblResults.Visible = true;
lblResults.ForeColor = System.Drawing.Color.Red;
lblResults.Text =
"An error has occurred loading data into the table view. ";
lblResults.Text += err.Message;
}
}
When run, the Gridview doesn't populate and the query (when investigated) it still has the variables and not the 'is nulls' or user inputs.
I think its something to so with the IF statements but i'm entirely sure. I think i just need another pair of eyes on this, any help would be appreciated.
Bit more info:
If i take out the sqlCommand bits it works perfectly with the IF statements, i'm trying to stop people from using malicious SQL queries.
This really isn't the correct way to use parameters. You should only assign values to them, not add comparison operators. Here's an example of how to "fix" your query for the #borcond parameter
...
AND ((#borcond = 'Select Borough' AND borough IS NOT NULL)
OR borough = #borcond)
...
Note: you don't need the equal sign with IS NOT NULL
And replace the if-else with
Command.Parameters.AddWithValue("#borcond", borsel);
You'll need to do similar changes for all of your parameters. The trick here is to basically move your if-else logic from the code into the sql query.
Additionally I don't think you need the location_address LIKE '%%' in your query as that just matches everything.
What juhar said. You've got the wrong idea about parameters. They're parameters and not text substitution. Here's an example of a valid query:
Select firstname, lastname from contacts
where ssn = #ssn
And in your code you'd say
Command.parameters.AddWithValue("#ssn","123-45-6789")

Response.Redirect won't send me to next page

I ran into a big problem here that I just dont know what to do in anymore.
Before I added the login system the Response.Redirect worked like a charm. But I know that the login works fine I ran debug on it and all the files works fine and goes on as it should.
EDIT 1: I noticed if I commentate Master.UserLogin(arr); out from the default btnLogin_click and type Server.Transfer(#"~\Admin\Side.aspx"); it works again but I dont see why making a session will stop the response?
EDIT 2: Okay so it seems like it has to do something with the site.master.cs where I create session varriabler and after tries to redirect to another page. how do I fix this?
Default.aspx.cs
protected void btnLogin_Click(object sender, EventArgs e)
{
db.ConnOpenHelpdesk();
if (db.HelpdeskDBLogin(txtBrugernavn.Text, txtPassword.Text).Count() == 8)
{
if (db.HelpdeskDBLogin(txtBrugernavn.Text, txtPassword.Text)[7] == "2" || db.HelpdeskDBLogin(txtBrugernavn.Text, txtPassword.Text)[7] == "1")
{
Master.UserLogin(db.HelpdeskDBLogin(txtBrugernavn.Text, txtPassword.Text));
}
}
else
{
db.ConnCloseHelpdesk();
lblError.ForeColor = Color.Red;
lblError.Visible = true;
lblError.Text = "Dit Brugernavn og Password passer ikke sammen prøv igen.";
}
//Master.UserLogin(txtBrugernavn.Text, txtPassword.Text);
}
DBControl.cs
public string[] HelpdeskDBLogin(string brugernavn, string password)
{
string sql = "SELECT * FROM Admin WHERE Brugernavn = '" + brugernavn + "' AND Password = '" + password + "'";
SqlCommand command = new SqlCommand(sql, m_helpdeskconnection);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
arr = new string[8] { "" + reader["ID"], "" + reader["Brugernavn"], "" + reader["Password"], "" + reader["Email"], "" + reader["TelefonNr"], "" + reader["Navn"], "" + reader["Nytpass"], "2" };
}
reader.Close();
return arr;
}
else
{
reader.Close();
string sql2 = "SELECT * FROM Kunder WHERE Brugernavn = '" + brugernavn + "' AND Password = '" + password + "'";
SqlCommand command2 = new SqlCommand(sql2, m_helpdeskconnection);
SqlDataReader reader2 = command2.ExecuteReader();
if (reader2.HasRows)
{
while (reader.Read())
{
arr = new string[8] { "" + reader["KundeNr"], "" + reader["Brugernavn"], "" + reader["Password"], "" + reader["Email"], "" + reader["TelefonNr"], "" + reader["Navn"], "" + reader["Nytpass"], "1" };
}
reader2.Close();
return arr;
}
else
{
reader2.Close();
string[] arr = new string[1];
return arr;
}
}
}
Site.Master.cs
public void UserLogin(string[] arr)
{
if (arr[7] == "1")
{
Session["Kundenr"] = arr[0];
Session["Brugernavn"] = arr[1];
Session["Email"] = arr[3];
Session["TelefonNr"] = arr[4];
Session["Kundenavn"] = arr[5];
Session["Nytpass"] = arr[6];
Session["Rang"] = arr[7];
Response.Redirect(#"~\Bruger\Side.aspx");
}
else if (arr[7] == "2")
{
Session["Kundenr"] = arr[0];
Session["Brugernavn"] = arr[1];
Session["Email"] = arr[3];
Session["TelefonNr"] = arr[4];
Session["Kundenavn"] = arr[5];
Session["Nytpass"] = arr[6];
Session["Rang"] = arr[7];
Response.Redirect(#"~\Admin\Side.aspx");
}
}
You are not setting authentication cookies. As a result, your user is redirected back to login screen since he does not have rights to view internal pages of your website.
Okay I found out what the problem was.
I had a Session created in string but I tested it inside my masterpage if it was an int and then it logged me out. so problem is solved ty for all of your time

Invalid attempt to call Read when reader is closed. getting this error?

Invalid attempt to call Read when reader is closed. getting this error asp.net with c#?
i have used this code
string catalogNo = string.Empty;
string deleteID = string.Empty;
Globals.Initialize("Text", "select CatelogNo,DeleteID from tbl_admin_quotation where QuotationID='" + quotation3 + "' order by id asc");
Globals.dr = Globals.cmd.ExecuteReader();
while (Globals.dr.Read() == true)
{
catalogNo = Globals.dr[0].ToString();
deleteID = Globals.dr[1].ToString();
decimal taqty = 0;
Globals.Initialize("Text", "select qty from tbl_admin_quotation where DeleteID='" + deleteID + "'");
Globals.dr3 = Globals.cmd.ExecuteReader();
if (Globals.dr3.Read() == true)
{
taqty = Convert.ToDecimal(Globals.dr3[0].ToString());
}
Globals.dr3.Dispose();
Globals.dr3.Close();
Globals.Initialize("Text", "select Pqty,Hqty from tbl_admin_stock where CatelogNo='" + catalogNo + "'");
Globals.dr = Globals.cmd.ExecuteReader();
if (Globals.dr.Read() == true)
{
if (Convert.ToDecimal(Globals.dr[0].ToString()) != 0)
{
Globals.Initialize("Text", "update tbl_admin_stock set Pqty=Pqty+'" + Convert.ToDecimal(taqty) + "' where CatelogNo='" + catalogNo + "'");
Globals.cmd.ExecuteNonQuery();
}
else if (Convert.ToDecimal(Globals.dr[1].ToString()) != 0)
{
Globals.Initialize("Text", "update tbl_admin_stock set Hqty=Hqty-'" + Convert.ToDecimal(taqty) + "' where CatelogNo='" + catalogNo + "'");
Globals.cmd.ExecuteNonQuery();
}
}
Globals.dr.Dispose();
Globals.dr.Close();
}
Globals.dr.Dispose();
Globals.dr.Close();
Globals.Initialize("Text", "delete from tbl_admin_quotation where QuotationId=#QuotationId");
Globals.cmd.Parameters.AddWithValue("#QuotationId", quotation3);
Globals.cmd.ExecuteNonQuery();
UpdatePanelMain.Update();
GridviewBind();
If you've code with obvious problems and problems you can't find, fix the obvious problems first and then the obscure problems will likely become obvious:
Get rid of the globals rubbish and put using in the appropriate places and then having the Dispose() called from that rather than explicitly will also fix this problem.

Categories

Resources