I have this code in C#:
private void sqlConnLabel()
{
NoIDPenghuni = new SqlParameter();
SqlConnection con = new SqlConnection(strCon);
com2 = new SqlCommand();
com2.Connection = con;
con.Open();
com2.CommandType = CommandType.StoredProcedure;
com2.CommandText = "label";
NoIDPenghuni.SqlDbType = SqlDbType.VarChar;
NoIDPenghuni.Size = 50;
NoIDPenghuni.ParameterName = "#NoIDPenghuni";
NoIDPenghuni.Value = NoIDPenghuniC;
NoIDPenghuni.Direction = ParameterDirection.Input;
com2.Parameters.Add(NoIDPenghuni);
string NamaPenghuni;
string JKPenghuni;
string NoTelpPenghuni;
string AlamatPenghuni;
string NoKamar;
NamaPenghuni = Convert.ToString(com2.ExecuteScalar());
JKPenghuni = Convert.ToString(com2.ExecuteScalar());
NoTelpPenghuni = Convert.ToString(com2.ExecuteScalar());
AlamatPenghuni = Convert.ToString(com2.ExecuteScalar());
NoKamar = Convert.ToString(com2.ExecuteScalar());
SqlDataReader reader = com2.ExecuteReader();
while (reader.Read())
{
NamaPenghuni = reader["NamaPenghuni"] == DBNull.Value ? null : (string)reader["NamaPenghuni"];
JKPenghuni = reader["JKPenghuni"] == DBNull.Value ? null : (string)reader["JKPenghuni"];
NoTelpPenghuni = reader["NoTelpPenghuni"] == DBNull.Value ? null : (string)reader["NoTelpPenghuni"];
AlamatPenghuni = reader["AlamatPenghuni"] == DBNull.Value ? null : (string)reader["AlamatPenghuni"];
NoKamar = reader["NoKamar"] == DBNull.Value ? null : (string)reader["NoKamar"];
}
label9.Text = NoIDPenghuniC;
label8.Text = NamaPenghuni;
if (JKPenghuni == "P")
label7.Text = "Male";
else
label7.Text = "Female";
label6.Text = NoTelpPenghuni;
label18.Text = AlamatPenghuni;
label5.Text = NoKamar;
con.Close();
}
When I try to run it keeps telling me
IndexOutOfRangeException was unhandled.
I think the data won't be fetched into my C#. It only takes the 'NamaPenghuni'
For example: if I take the data with NoIDPenghuni='110801101, the NamaPenghuni should be Priska Hapsari, the JKPenghuni should be W, the NoTelpPenghuni should be 08567711332, and the AlamatPenghuni should be Jl. Mega Cinere No. 29, Cinere.
But on my locals section I can see that all those string variables values are Priska Hapsari.
What did I do wrong?
You call for 5 times the ExecuteScalar before the ExecuteReader.
ExecuteScalar returns the first column of the first row (just one result).
Calling it 5 times results in the same value for the all 5 variables
The IndexOutOfRange exception could be caused by the following ExecuteReader that expects to find 5 columns in the returned values, but we can't see if the StoredProcedure returns effectively 5 values per row
Related
I have an attendancesheet program. I have triple checked my database tables and all of their columns are null. I said if they are not null go through but although all of them are null it goes through them all :D I don't know whats wrong.
private void textBoxX1_KeyDown(object sender, KeyEventArgs e)
{
sqlcon.Close();
sqlcon.Open();
if (e.KeyCode == Keys.Enter)
{
string t = lbl_Time.Text;
string d = lbl_Date.Text;
string selectQueryName = "SELECT name FROM tbl_attendanceMembers where memberCode=" + "'" + textBoxX1.Text + "'";
var sqlcmdName = new SqlCommand(selectQueryName, sqlcon);
var resultName = sqlcmdName.ExecuteScalar();
string selectQueryId = "SELECT MAX(id) FROM tbl_attendanceSheet";
var sqlcmdId = new SqlCommand(selectQueryId, sqlcon);
var resultId = sqlcmdId.ExecuteScalar();
(1)if (resultId != null)
{
string selectQueryCockin = "SELECT Clockin FROM tbl_attendanceSheet where id=" + "resultId";
var sqlcmdCockin = new SqlCommand(selectQueryCockin, sqlcon);
var resultCockin = sqlcmdId.ExecuteScalar();
(2)if (resultCockin != null)
{
(3)if (resultName != null)
{
this.lbl_mmbrname.Text = resultName.ToString();
this.lbl_timestored.Text = t;
textBoxX1.Clear();
}
}
}
else //if result id == null
{
sqlcon.Open();
SqlCommand sqlcmdClockin = new SqlCommand("InputClockIn", sqlcon);
sqlcmdClockin.CommandType = CommandType.StoredProcedure;
sqlcmdClockin.Parameters.AddWithValue("#InputDate", d);
sqlcmdClockin.Parameters.AddWithValue("#InputTime", t);
sqlcmdClockin.ExecuteNonQuery();
SqlDataAdapter sqlda = new SqlDataAdapter("SELECT * FROM tbl_attendanceMembers", sqlcon);
DataTable dt = new DataTable();
sqlda.Fill(dt);
dataGridView1.DataSource = dt;
}
sqlcon.Close();
}
}
When I execute this code, it equals lbl_mmbrname.Text to resultName and lbl_timestored.Text = t. So it means it has gone through all the way down into the 3rd if statement which is false...
I have checked it via break poits(f9).
By the first sqlcon.close(); is because if I dont write it it will say connection is not closed which doesn't make sense to me because I have written a sqlcon.close(); down there...
According to this if on a DbCommand.ExecuteScalar()the database returns null your query gets a DbNull.Value object returned.
So I guess you need to check for that instead of null
EDIT
Relevant remark there:
If the first column of the first row in the result set is not found, a null reference is returned. If the value in the database is null, the query returns DBNull.Value.
so it can return both a null and DBNull.Value
I am trying to insert data into a SQL table. The data types I am having issues with are nullable floats. When the NULL values are inserted they change to 0. How can I keep them NULL.
private void InsertStatisticsData(DataTable dt)
{
//check isin periodicity and As of Date
foreach(DataRow row in dt.Rows)
{
DataTable queryResultTable = SQL.Query($#"SELECT * FROM Statistics
WHERE [CodeID] = '{row["CodeID"]}'
AND [Periodicity] = '{row["Periodicity"]}'
AND [As of Date] = '{row["As of Date"]}'");
if(queryResultTable.Rows.Count == 0)
{
//Check for Null Values
for(int i = 0; i < row.ItemArray.Count(); i++)
{
if (Convert.ToString(row[i]) == "")
row[i] = (object)DBNull.Value;
}
//Insert Data Into DataBase
SQL.NonQuery($#"INSERT INTO Statistics
VALUES ('{row["CodeID"]}' ,
'{row["Volatility"]}',
'{row["Beta"]}',
'{row["Info Ratio"]}',
'{row["Tracking"]}',
'{row["Drawdown"]}',
'{row["Periodicity"]}',
'{row["As of Date"]}')");
}
}
}
Nonquery Function:
public static void NonQuery(string query, string databaseName = "Database", string serverAddress = "server-name", int commandTimeout = 30)
{
string connString = $"Server = {serverAddress}; Database = {databaseName}; Trusted_Connection = True";
using (SqlConnection sqlConn = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand(query, sqlConn))
{
sqlConn.Open();
cmd.CommandTimeout = commandTimeout;
cmd.ExecuteNonQuery();
}
}
You need to make sure your database column structure contains NULL types where you actually need them.
Also make sure you don't have any default constraints set, which automatically values the columns to 0 when null is assigned.
if(Convert.ToString(null) == "")
will be evaluated as false.
so below code won't get executed
row[i] = (object)DBNull.Value;
on a side note, you should use SqlParameters instead of appending values in a string.
This may seem a little heavy handed and bloaty, but if you use parameters (and you really, truly should), I have an extention method I use in my project to take any command object and loop through the parameters to turn a .NET null into a DbNull:
private static void ProcessNullParameters(this DbCommand command)
{
foreach (DbParameter param in command.Parameters)
{
if (param.Value == null)
param.Value = DBNull.Value;
}
}
This way, if your native object returns a null value, you can call the extention method against the command object. I couldn't tell what your SQL object was in your example (a framework of some type?), but presumably, somewhere behind the scenes something like this would be going on:
SqlCommand cmd = new SqlCommand("insert into Statistics values (#Code, #Volatility)", conn);
cmd.Parameters.Add("#Code", SqlDbType.VarChar);
cmd.Parameters.Add("#Volatility", SqlDbType.Decimal);
foreach (DataRow dr in dt.Rows)
{
cmd.Parameters[0].Value = dr["Code"];
cmd.Parameters[1].Value = dr["Volatility"];
// And here you convert your nulls to DbNull
cmd.ProcessNullParameters();
cmd.ExecuteNonQuery();
}
The alternative would be to do this on every value declaration that is nullable.
cmd.Parameters[0].Value = dr["Code"] ?? DbNull.Value
cmd.Parameters[1].Value = dr["Volatility"] ?? DbNull.Value;
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.
I have in stored procedure in SQL Server that use function and return RESULT a decimal.
In C# I need to get it but I get an error :
"INVALLD CastEXCEPTION was unhandeld by user code" "an exception of
type 'system.invaildCastException' occured...'
My C# code:
decimal? val = null;
SqlConnection con = new SqlConnection(conStr);
con.Open();
using (con)
{
SqlCommand cmd = new SqlCommand("dbo.spSetOrderDetails", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter tvpParam = cmd.Parameters.AddWithValue("#OrderDetailsItemsTVP", dt);
tvpParam.SqlDbType = SqlDbType.Structured;
// this part of code return the SUM
SqlParameter returnParam = cmd.Parameters.Add("#RESULT", SqlDbType.Decimal);
returnParam.Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
val = (decimal)cmd.Parameters["#RESULT"].Value;--HERE I GET THE EXCEPTION
}
con.Close();
return (decimal)val;
You can't cast the parameter with ParameterDirection.ReturnValue to a datatype that is not an integer.
The RETURN statement in T-SQL can only return integer values.
However, if you are absolutely certain that your Stored Procedure ends always with something like RETURN xxx then you could
val = Convert.ToDecimal(cmd.Parameters["#RESULT"].Value);
var res = cmd.Parameters["#RESULT"];
if(res != null && res.Value != null && res.Value != DbNull.value){
val = Convert.ToDecimal(res.Value);
}
else
val = defaultvalue;
This code will check if it's null or equal to dbnull.value. It will only cast if it's not null or dbnull.value. In case of null (or dbnull.value) it will simply set the value to defaultvalue for decimal.
Error shown on the website. Im using asp net visual C# webform, access data source (MS access) When I click on Add to Cart button on productdetails.aspx
Line 41: int intOrderNo = (int)Session["sOrderNo"];
Line 42: string strUnitPrice = (string)Session["sUnitPrice"];
Line 43: decimal decUnitPrice = decimal.Parse(strUnitPrice);
For myOrder table in Ms Access
There is oOrderNo, oDate, oUserName, oPaymentMode, oStatus,
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
// test to remind customer to login first
if ((string)Session["sFlag"]!="T")
{
Type csType = this.GetType();
ClientScript.RegisterStartupScript(csType, "Error", scriptErrorLogin);
}
// Connect to database
OleDbConnection mDB = new OleDbConnection();
mDB.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0;Data source=" + Server.MapPath("~/App_Data/webBase.accdb");
mDB.Open();
OleDbCommand cmd;
DetailsViewRow row0 = DetailsView1.Rows[0];
string strProductID = row0.Cells[1].Text;
mDB.Close();
// save as session variables
Session["sProductID"] = strProductID;
DetailsViewRow row4 = DetailsView1.Rows[4];
Session["sUnitPrice"] = row4.Cells[1].Text;
int intOrderNo = (int)Session["sOrderNo"];
string strUnitPrice = (string)Session["sUnitPrice"];
decimal decUnitPrice = decimal.Parse(strUnitPrice);
string strSQL = "INSERT INTO orderItems(uOrderNo, uProductID, uUnitPrice)" + "VALUES(#eOrderNo, #eProductID, #eUnitPrice)";
cmd = new OleDbCommand(strSQL, mDB);
cmd.Parameters.AddWithValue("#eOrderNo", intOrderNo);
cmd.Parameters.AddWithValue("#eProductID", strProductID);
cmd.Parameters.AddWithValue("#eUnitPrice", decUnitPrice);
mDB.Open();
cmd.ExecuteNonQuery();
mDB.Close();
Response.Redirect("ShoppingCart.aspx");
Try this
Line 41: int intOrderNo = Session["sOrderNo"] == DBNull.Value ? 0 : (int)Session["sOrderNo"];
Line 42: string strUnitPrice = Session["sUnitPrice"] == DBNull.Value ? string.Empty : (string)Session["sUnitPrice"];
null Vs DBNull.Value
Try below code :
Line 41: int intOrderNo = Session["sOrderNo"] == null ? 0 : (int)Session["sOrderNo"];
Line 42: string strUnitPrice = Session["sUnitPrice"] == null ? string.Empty : (string)Session["sUnitPrice"];
Line 43: decimal decUnitPrice = string.IsNullOrWhiteSpace(strUnitPrice) ? 0 : decimal.Parse(strUnitPrice);
Just check that if Session variable is Null-
if( Session["sOrderNo"] != null && all the session variables )
{
//Now check your condition here
}
else {
//Perform any operation
}