I'm working with sql databases via ado.net in c# and I'm trying to pass the following update command:
cmd.CommandText = #"UPDATE VehicleContract SET regNr='#reg', assoc_id='#assort', percentage='#perc', vehicleType='#type', trailerNr='#trailer' WHERE contractId='#id'";
cmd.Parameters.AddWithValue("#id", id);
id is in int. I read it as an int. I even do a int.Parse(txtbox.text) and everything is fine. But then when I insert all the values in the boxes, press submit. I get the conversion error saying that it can't convert '#id' varchar to int... it makes no sense
Is there any specific thing I'm not doing right? Need any more details?
The whole code:
if (tbid.Text == "" || tbper.Text == "" || tbas.Text == "" || tbvt.Text == "")
{
MessageBox.Show("All fields must be filled ");
return;
}
if (tbreg.Text == "" && tbtn.Text == "")
{
MessageBox.Show("Fill at least one from: Registration nr or trailer nr");
return;
}
int id = 0;
string reg = "";
int assort = 0;
int perc = 0;
string type = "";
int trailer = 0;
try
{
id = int.Parse(tbid.Text);
Console.Write(id);
if (tbreg.Text != "")
{
reg = tbreg.Text;
}
assort = int.Parse(tbas.Text);
perc = int.Parse(tbper.Text);
type = tbvt.Text;
if (tbtn.Text != "")
{
trailer = int.Parse(tbtn.Text);
}
}
catch (Exception ee)
{
MessageBox.Show("id, assoc, perc and trailer nr must be integers ");
return;
}
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
con.ConnectionString = "Data Source=.;initial Catalog=Lab5;integrated security=true";
con.Open();
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"UPDATE VehicleContract SET regNr='#reg', assoc_id='#assort', percentage='#perc', vehicleType='#type', trailerNr='#trailer' WHERE contractId='#id'";
cmd.Parameters.AddWithValue("#id", id);
if (reg == "")
{
cmd.Parameters.AddWithValue("#reg", DBNull.Value);
}
else
{
cmd.Parameters.AddWithValue("#reg", reg);
}
cmd.Parameters.AddWithValue("#assort", assort);
cmd.Parameters.AddWithValue("#perc", perc);
cmd.Parameters.AddWithValue("#type", type);
if (trailer == 0)
{
cmd.Parameters.AddWithValue("#trailer", DBNull.Value);
}
else
{
cmd.Parameters.AddWithValue("#trailer", trailer);
}
cmd.Connection = con;
SqlDataReader sdr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(sdr);
childgrid.DataSource = dt;
sdr.Close();
con.Close();
When you use WHERE contractId='#id' in a query you are comparing the int contractId column with the string '#id' value.
You need to use WHERE contractId=#id.
So remove single quotes around #id and other parameters.
Related
An error is thrown when there is no data in data base while converting a string value into int.
try {
SqlCommand cmdc = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=1 AND Crdt_typ_id=1", con);
string companya_credit_amount = null, comapnyb_credit_amount = null;
con.Open();
SqlDataReader drc = cmdc.ExecuteReader();
if (drc.HasRows)
{
while (drc.Read())
{
companya_credit_amount = drc[0].ToString();
}
drc.Close();
con.Close();
}
SqlCommand cmdcp = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=2 AND Crdt_typ_id=1", con);
con.Open();
SqlDataReader drcp = cmdcp.ExecuteReader();
if (drcp.HasRows)
{
while (drcp.Read())
{
companyb_credit_amount = drcp[0].ToString();
}
drcp.Close();
con.Close();
}
if (!Page.IsPostBack)
{
int companyA = 0,companyB=0;
if (companya_credit_amount != "") { companyA = Convert.ToInt32(credit_amount.ToString()); }
if (companyb_credit_amount != ""){ companyB = Convert.ToInt32(companyb_credit_amount); }
int total = (companyA+companyB);
count_total_lbl.Text = "Rs." + " " + total.ToString();
count_comapnya_lbl.Text = "Rs." + " " + companya_credit_amount.ToString();
count_companyb_lbl.Text ="Rs."+" "+ companyb_credit_amount.ToString();
}
}
catch(Exception ex) { Label2.Text = ex.ToString(); }
If there is value its working fine.but when there is no value in data base there is an error msg.
System.FormatException: Input string was not in a correct format.
Use IsDBNull to check for null values
Create and destroy all your type instances that implement IDisposable in using blocks. This ensures that connections are always released and resources are cleaned up.
Do not use connections across a class. Create them when needed and then dispose of them. Sql Server will handle connection pooling.
Get the native types directly, not the string equivalent! See changes to GetInt32 instead of ToString on the data reader.
You should refactor this to use SqlParameter's and make the retrieval statement generic OR get both SUM values in 1 sql call.
There is an if (!Page.IsPostBack) statement, if none of this code does anything if it is a postback then check at the top of the page and do not execute the sql statements if it is a postback. Otherwise the code is making (possibly) expensive sql calls for no reason.
try
{
int companyA = 0,companyB=0;
using(var con = new SqlConnection("connectionStringHere"))
{
con.Open();
using(SqlCommand cmdc = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=1 AND Crdt_typ_id=1", con))
using(SqlDataReader drc = cmdc.ExecuteReader())
{
if (drc.Read() && !drc.IsDBNull(0))
companyA = drc.GetInt32(0);
}
using(SqlCommand cmdcp = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=2 AND Crdt_typ_id=1", con))
using(SqlDataReader drcp = cmdcp.ExecuteReader())
{
if (drcp.Read() && !drcp.IsDBNull(0))
companyB = drcp.GetIn32(0);
}
}
// if you are not going to do anything with these values if its not a post back move the check to the top of the method
// and then do not execute anything if it is a postback
// ie: // if (Page.IsPostBack) return;
if (!Page.IsPostBack)
{
int total = (companyA+companyB);
count_total_lbl.Text = "Rs." + " " + total.ToString();
count_comapnya_lbl.Text = "Rs." + " " + companyA.ToString();
count_companyb_lbl.Text ="Rs."+" "+ companyB.ToString();
}
}
catch(Exception ex) { Label2.Text = ex.ToString(); }
Try to replace this
SELECT SUM(Credited_amount)
WITH
SELECT ISNULL(SUM(Credited_amount),0)
Also find one confusing code while converting Credited amount values
if (companya_credit_amount != "") { companyA = Convert.ToInt32(credit_amount.ToString()); }
---------^^^^^
if (companyb_credit_amount != ""){ companyB = Convert.ToInt32(companyb_credit_amount); }
I don't know about your business requirement but What i think Instead of using credit_amount value companya_credit_amount should be use to show value for companyA variable right?
You should do 2 things:
string companya_credit_amount = "", comapnyb_credit_amount = "";
Before assigning the value to these string variable you should check for db null as following:
while (drc.Read())
{
companya_credit_amount = (drc[0] != DbNull.Value) ? drc[0].ToString() : "" ;
}
Similarely
while (drcp.Read())
{
companyb_credit_amount = (drcp[0] != DbNull.Value) ? drcp[0].ToString() : "";
}
Try it.
You need to initialize credit_amount to empty and check if db value is null as shown below:
try {
companya_credit_amount = string.Empty;
companyb_credit_amount = string.Empty;
SqlCommand cmdc = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=1 AND Crdt_typ_id=1", con);
string companya_credit_amount = null, comapnyb_credit_amount = null;
con.Open();
SqlDataReader drc = cmd
c.ExecuteReader();
if (drc.HasRows)
{
while (drc.Read())
{
companya_credit_amount = drcp.IsDBNull(0)?string.Empty:Convert.ToString(drcp[0]);
}
drc.Close();
con.Close();
}
SqlCommand cmdcp = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=2 AND Crdt_typ_id=1", con);
con.Open();
SqlDataReader drcp = cmdcp.ExecuteReader();
if (drcp.HasRows)
{
while (drcp.Read())
{
companyb_credit_amount = drcp.IsDBNull(0)?string.Empty:Convert.ToString(drcp[0]);
}
drcp.Close();
con.Close();
}
if (!Page.IsPostBack)
{
int companyA = 0,companyB=0;
if (companya_credit_amount != "") { companyA = Convert.ToInt32(credit_amount.ToString()); }
if (companyb_credit_amount != ""){ companyB = Convert.ToInt32(companyb_credit_amount); }
int total = (companyA+companyB);
count_total_lbl.Text = "Rs." + " " + total.ToString();
count_comapnya_lbl.Text = "Rs." + " " + companya_credit_amount.ToString();
count_companyb_lbl.Text ="Rs."+" "+ companyb_credit_amount.ToString();
}
}
catch(Exception ex) { Label2.Text = ex.ToString(); }
Can somebody help understand this code?
protected void Page_Load(object sender, EventArgs e)
{
Database database = new Database();
OleDbConnection conn = database.connectDatabase();
if (Request.Cookies["BesteldeArtikelen"] == null)
{
lbl_leeg.Text = "Er zijn nog geen bestelde artikelen";
}
else
{
HttpCookie best = Request.Cookies["BesteldeArtikelen"];
int aantal_bestel = best.Values.AllKeys.Length;
int[] bestelde = new int[aantal_bestel];
int index = 0;
foreach (string art_id in best.Values.AllKeys)
{
int aantalbesteld = int.Parse(aantalVoorArtikel(int.Parse(art_id)));
int artikel_id = int.Parse(art_id); // moet getalletje zijn
if (aantalbesteld != 0)
{
bestelde[index] = artikel_id;
}
index++;
}
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT artikel_id, naam, prijs, vegetarische FROM artikel WHERE artikel_id IN (" +
String.Join(", ", bestelde) + ")";
try
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
}
catch (Exception error)
{
errorMessage.Text = error.ToString();
}
finally
{
conn.Close();
}
}
}
And there is this part of code i dont really understand:
public string aantalVoorArtikel(object id)
{
int artikel_id = (int)id;
if (Request.Cookies["BesteldeArtikelen"] != null &&
Request.Cookies["BesteldeArtikelen"][artikel_id.ToString()] != null)
{
return Request.Cookies["BesteldeArtikelen"][artikel_id.ToString()];
}
else
{
return "0";
}
}
It extracts values from a cookie and builds an int array. (Displays a message if the cookie value is null) The int array is then used as the value for the SQL IN operator when querying the database. The result set is then bound to the GridView.
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.
In my Page I am fetching a value from the Database & filling the values in the DataTable. I am then comparing that values with the mac String in the IF.
Based upon the condition in the Query there will be no records fetched, it is stuck in the IF condition and throws the No row at Position 0 Exception rather than going into the Else part.
My code is:
string mac = GetMac();
string Qry = "Select VUserid,Password from passtable where VUserid='" + UserName.Text + "' and Flag='A'";
string qry = "Select VUserid,Password from passtable where Flag='A'";
string strq = "Select Mac_id from Sysinfo Where Appflag='A'";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["EvalCon"].ConnectionString))
{
try
{
SqlCommand cmd = new SqlCommand(Qry, conn);
SqlCommand cmd1 = new SqlCommand(qry, conn);
SqlCommand cmd2 = new SqlCommand(strq, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataAdapter daa = new SqlDataAdapter(cmd1);
SqlDataAdapter dap = new SqlDataAdapter(cmd2);
DataTable dt = new DataTable();
DataTable dtt = new DataTable();
DataTable tab = new DataTable();
da.Fill(dt);
daa.Fill(dtt);
dap.Fill(tab);
for (int i = 0; i < tab.Rows.Count; i++)
{
for (int x = 0; x <= dtt.Rows.Count - 1; x++)
{
if (mac == tab.Rows[i]["Mac_id"].ToString() || tab.Rows.Count != 0)
{
if (UserName.Text == dtt.Rows[x]["VUserid"].ToString() && Password.Text == dtt.Rows[x]["Password"].ToString())
{
Response.Redirect("~/Changepass.aspx");
break;
}
else
{
lblMessage.Visible = true;
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Invalid Username or Password !!!";
}
}
else
{
lblMessage.Visible = true;
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Invalid Access Point for Evaluation !!!";
}
}
}
}
finally
{
conn.Close();
conn.Dispose();
}
}
First of all, you may want to give some more meaningful names to your variables.
On a side note, you may want to change your for loops into a foreach loop:
foreach (DataRow tabRow in tab.Rows.Count)
{
foreach (DataRow dttRow in dtt.Rows.Count)
{
// logic here
// tab.Rows[i]["Mac_id"] becomes tabRow["Mac_id"]
// and
// dtt.Rows[x]["VUserid"] becomes dttRow["VUserid"]
// and so on...
}
}
This way if there are no records fetched it won't go in.
After that, you may want to check the conditions on RowCount > 0 for the datatables before going inside the loops and act outside the loop if the RowCount is 0.
Just swap your OR condition in If statement:
if (tab.Rows.Count != 0 || mac == tab.Rows[i]["Mac_id"].ToString())
{
...
...
}
If you need to check against a null result I'd wrap my if statement in another if statement that does a simple check for a null result before doing anything else. Something like this will check if it's not null:
if(tab.rows[i]["Mac_id"] != null)
{
//logic here
}
You could add this into your current if statement check so:
if(mac == tab.Rows[i]["Mac_id"].ToString() || tab.Rows.Count != 0)
becomes:
if(mac == tab.Rows[i]["Mac_id"].ToString() || tab.Rows.Count != 0 && tab.rows[i]["Mac_id"] != null)
Though as Tallmaris says it might be better to restructure it using a foreach loop instead.
I have a ugly code that can't be reused. I have many similar queries. I want to rewrite it with SqlParameterCollectionExtensions or other better ways. But I don't know about SqlParameterCollectionExtensions at all.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
SqlConnection con = new SqlConnection(strCon);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "UPDATE Problem_DE SET ProbDesc = #ProbDesc, field_1 = #field_1, field_2 = #field_2, field_3 = #field_3, field_4 = #field_4, field_5 = #field_5, field_6 = #field_6, field_7 = #field_7 WHERE (ProbId = #ProbId)";
if (e.NewValues["ProbDesc"] == null)
cmd.Parameters.AddWithValue("#ProbDesc", DBNull.Value);
else
cmd.Parameters.AddWithValue("#ProbDesc", e.NewValues["ProbDesc"]);
if (e.NewValues["field_1"] == null)
cmd.Parameters.AddWithValue("#field_1", DBNull.Value);
else
cmd.Parameters.AddWithValue("#field_1", e.NewValues["field_1"]);
if (e.NewValues["field_2"] == null)
cmd.Parameters.AddWithValue("#field_2", DBNull.Value);
else
cmd.Parameters.AddWithValue("#field_2", e.NewValues["field_2"]);
if (e.NewValues["field_3"] == null)
cmd.Parameters.AddWithValue("#field_3", DBNull.Value);
else
cmd.Parameters.AddWithValue("#field_3", e.NewValues["field_3"]);
if (e.NewValues["field_4"] == null)
cmd.Parameters.AddWithValue("#field_4", DBNull.Value);
else
cmd.Parameters.AddWithValue("#field_4", e.NewValues["field_4"]);
\\ blah blah
cmd.ExecuteNonQuery();
con.Close();
}
The sql parameters come from e or textbox etc.
Thanks.
Maybe something like this? I assume the problem is that you have a variable number of values, depending on the problem table?
private void UpdateProblem(string problemName, string problemDescription, int problemId, object[] fieldValues)
{
SqlConnection con = null;
SqlCommand cmd = new SqlCommand();
StringBuilder sql = new StringBuilder();
int fieldCounter = 1;
// start building the sql statement
sql.AppendFormat("UPDATE {0} SET ProbDesc = #ProbDesc", problemName);
// add the 'description' parameter
cmd.Parameters.Add(new SqlParameter("#ProbDesc", problemDescription));
// add each field value to the update statement... the SqlParameter will infer the database type.
foreach(object fieldValue in fieldValues)
{
// add additional SET clauses to the statement
sql.AppendFormat(",field{0} = #field{0}", fieldCounter);
// add the field parameter to the command's collection
cmd.Parameters.Add(new SqlParameter(String.Format("#field{0}", fieldCounter), fieldValue));
fieldCounter++;
}
// finish up the SQL statement by adding the where clause
sql.Append(" WHERE (ProbId = #ProbId)");
// add the 'problem ID' parameter to the command's collection
cmd.Parameters.Add(new SqlParameter("#ProbId", problemId));
// finally, execute the SQL
try
{
con.Open();
cmd.Connection = con;
cmd.CommandText = sql.ToString();
cmd.ExecuteNonQuery();
}
catch(SqlException ex)
{
// do some exception handling
}
finally
{
if(con != null)
con.Dispose();
}
}
An example to call this code would be:
public void UpdateProblemDe()
{
int problemId = FetchCurrentProblemId();
string field1 = e.NewValues["field_1"];
string field2 = e.NewValues["field_2"];
string field3 = ddlField3.SelectedValue;
int field4 = Convert.ToInt32(e.NewValues["field_4"]);
string field5 = txtField5.Text;
DateTime field6 = DateTime.Now.AddSeconds(Convert.ToInt32(ddlField6.SelectedValue));
string field7 = txtField7.Text;
object[6] fieldValues;
if(field1 != null)
fieldValues[0] = field1;
else
fieldValues[0] = DBNull.Value;
if(field2 != null)
fieldValues[1] = field2;
else
fieldValues[1] = DBNull.Value
fieldValues[2] = field3;
fieldValues[3] = field4;
fieldValues[4] = field5;
fieldValues[5] = field6;
fieldValues[6] = field7;
UpdateProblem("Problem_DE", "Houston, we have a problem", problemId, fieldValues);
}
The example code above is obviously just a demonstration of how to make an array of objects stored from page control values and doesn't include any data validation that you will need to implement in production code.
If you won't know how big the object[] array needs to be at runtime, you can change it to be a generic List of objects and add the items dynamically.
Based on this answer
Create new SQLCommand's or reuse the same one
you could refactor your code the following way
public class DbHepler
{
private readonly string _connectionString;
public DbHepler(string connectionString)
{
_connectionString = connectionString;
}
public void ExecuteNonQuery(string query)
{
ExecuteNonQuery(query, null);
}
public void ExecuteNonQuery(string query, Dictionary<string, object> parameters)
{
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = query;
if (parameters != null)
{
foreach (string parameter in parameters.Keys)
{
cmd.Parameters.AddWithValue(parameter, parameters[parameter] ?? DBNull.Value);
}
}
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
}
your code will look something like:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string query = "UPDATE Problem_DE SET ProbDesc = #ProbDesc, field_1 = #field_1, field_2 = #field_2, field_3 = #field_3, field_4 = #field_4, field_5 = #field_5, field_6 = #field_6, field_7 = #field_7 WHERE (ProbId = #ProbId)";
Dictionary<string, object> parameters = new Dictionary<string, object>();
if (e.NewValues["ProbDesc"] == null)
parameters.Add("#ProbDesc", null);
else
parameters.Add("#ProbDesc", e.NewValues["ProbDesc"]);
//blah blah
DbHepler dbHepler = new DbHepler("your sql connection info");
dbHepler.ExecuteNonQuery(query, parameters);
}