Am trying to insert several columns into my database using the following insert query from C# but it throws the exception somehow somewhere and my guess is there are no values provided for insertion. i just want to confirm that and find out how i can fix the insert statement. i have a picture below that displays what is passed into the parameters at runtime. i used a break point to get this info.
need your expertise at this one...thanks
if (Page.IsValid)
{
DateTime exhibitDate = DateTime.Now;
int caseid = Convert.ToInt32(CaseIDDropDownList.SelectedItem.Text);
string exhibittype = exhibitTypeTextBox.Text.ToString();
string storedloc = storedLocationTextBox.Text.ToString();
string offid = DropDownList1.SelectedItem.Text.ToString();
Stream imgStream = exhibitImageFileUpload.PostedFile.InputStream;
int imgLen = exhibitImageFileUpload.PostedFile.ContentLength;
byte[] imgBinaryData = new byte[imgLen];
int n = imgStream.Read(imgBinaryData,0,imgLen);
try
{
SqlConnection connections = new SqlConnection(strConn);
SqlCommand command = new SqlCommand("INSERT INTO Exhibits (CaseID, ExhibitType, ExhibitImage, DateReceived, StoredLocation, InvestigationStatus, OfficerID, SuspectID, InvestigatorID, ManagerID, AdminID ) VALUES (#CaseID, #ExhibitType, #ExhibitImage, #DateReceived, #StoredLocation, #InvestigationStatus, #OfficerID, #SuspectID, #InvestigatorID, #ManagerID, #AdminID)", connections);
SqlParameter param0 = new SqlParameter("#CaseID", SqlDbType.Int);
param0.Value = caseid;
command.Parameters.Add(param0);
SqlParameter param1 = new SqlParameter("#ExhibitType", SqlDbType.NText);
param1.Value = exhibittype;
command.Parameters.Add(param1);
SqlParameter param2 = new SqlParameter("#ExhibitImage", SqlDbType.Image);
param2.Value = imgBinaryData;
command.Parameters.Add(param2);
SqlParameter param3 = new SqlParameter("#DateReceived", SqlDbType.SmallDateTime);
param3.Value = exhibitDate;
command.Parameters.Add(param3);
SqlParameter param4 = new SqlParameter("#StoredLocation", SqlDbType.NText);
param4.Value = storedloc;
command.Parameters.Add(param4);
SqlParameter param5 = new SqlParameter("#InvestigationStatus", SqlDbType.VarChar, 50);
param5.Value = "";
command.Parameters.Add(param5);
SqlParameter param6 = new SqlParameter("#OfficerID", SqlDbType.NChar, 10);
param6.Value = offid;
command.Parameters.Add(param6);
SqlParameter param7 = new SqlParameter("#SuspectID", SqlDbType.NChar, 10);
param7.Value = null;
command.Parameters.Add(param7);
SqlParameter param8 = new SqlParameter("#InvestigatorID", SqlDbType.NChar, 10);
param8.Value = null;
command.Parameters.Add(param8);
SqlParameter param9 = new SqlParameter("#ManagerID", SqlDbType.NChar, 10);
param9.Value = null;
command.Parameters.Add(param9);
SqlParameter param10 = new SqlParameter("#AdminID", SqlDbType.NChar, 10);
param10.Value = adminID;
command.Parameters.Add(param10);
connections.Open();
int numRowsAffected = command.ExecuteNonQuery();
connections.Close();
if (numRowsAffected != 0)
{
Response.Write("<BR>Rows Inserted successfully");
CaseIDDropDownList.ClearSelection();
exhibitTypeTextBox.Text = null;
storedLocationTextBox.Text = null;
DropDownList1.ClearSelection();
}
else
{
Response.Write("<BR>An error occurred uploading the image");
}
}
catch (Exception ex)
{
string script = "<script>alert('" + ex.Message + "');</script>";
}
the exception is as follows
$exception {"The parameterized query '(#CaseID int,#ExhibitType ntext,#ExhibitImage image,#DateReceive' expects the parameter '#SuspectID', which was not supplied."} System.Exception {System.Data.SqlClient.SqlException}
If you want to pass in NULL for your database / parameter type, you need to use DBNull.Value like this:
SqlParameter param9 = new SqlParameter("#ManagerID", SqlDbType.NChar, 10);
param9.Value = DBNull.Value;
command.Parameters.Add(param9);
Do this wherever you're setting something to null right now, and I'm pretty sure it'll work just fine. Everything is looking okay.
You can do this much easier, try it as such:
if (Page.IsValid)
{
DateTime exhibitDate = DateTime.Now;
int caseid = Convert.ToInt32(CaseIDDropDownList.SelectedItem.Text);
string exhibittype = exhibitTypeTextBox.Text.ToString();
string storedloc = storedLocationTextBox.Text.ToString();
string offid = DropDownList1.SelectedItem.Text.ToString();
Stream imgStream = exhibitImageFileUpload.PostedFile.InputStream;
int imgLen = exhibitImageFileUpload.PostedFile.ContentLength;
byte[] imgBinaryData = new byte[imgLen];
int n = imgStream.Read(imgBinaryData,0,imgLen);
try
{
SqlConnection connections = new SqlConnection(strConn);
SqlCommand command = new SqlCommand("INSERT INTO Exhibits (CaseID, ExhibitType, ExhibitImage, DateReceived, StoredLocation, InvestigationStatus, OfficerID, SuspectID, InvestigatorID, ManagerID, AdminID ) VALUES (#CaseID, #ExhibitType, #ExhibitImage, #DateReceived, #StoredLocation, #InvestigationStatus, #OfficerID, #SuspectID, #InvestigatorID, #ManagerID, #AdminID)", connections);
command.Parameters.AddWithValue("#CaseID", caseid);
//and so on for your 10 parameters
connections.Open();
int numRowsAffected = command.ExecuteNonQuery();
connections.Close();
if (numRowsAffected != 0)
{
Response.Write("<BR>Rows Inserted successfully");
CaseIDDropDownList.ClearSelection();
exhibitTypeTextBox.Text = null;
storedLocationTextBox.Text = null;
DropDownList1.ClearSelection();
}
else
{
Response.Write("<BR>An error occurred uploading the image");
}
}
catch (Exception ex)
{
string script = "<script>alert('" + ex.Message + "');</script>";
}
}
I'm not sure if this will actually fix what is happening without knowing the exact exception. If you could provide the actual exception that would help a lot.
Related
Anyone can help? All day I can not understand why I get an error.
Error is:
SqlParameter with ParameterName '#FKTO' is not included in SqlParameterCollection
Maybe there is an easier way to get data from the CSV file and substitute data from other tables in columns with foreign key.
private void insertInTab()
{
try
{
sqlConnection = new SqlConnection(ConnectionMSSQLServer);
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
const string strQueryRechnung = #"IF NOT EXISTS (SELECT Menge, Einheit, BetragBrutto, Beginn, Ende, tblFkto.IdFKTO AS IdF, tblGeraet.Id_Geraet AS IdG
FROM tblRechnung, tblFkto, tblGeraet
WHERE
tblFkto.FKTO = #FKTO
AND tblGeraet.Bezeichnung = #Bezeichnung
AND Menge = #Menge
AND Einheit = #Einheit
AND BetragBrutto = #BetragBrutto
AND Beginn = #Beginn
AND Ende = #Ende)
INSERT INTO tblRechnung (Menge, Einheit, BetragBrutto, Beginn, Ende, IdFKTO, IdGeraet)
VALUES (#Menge, #Einheit, #BetragBrutto, #Beginn, #Ende, tblFkto.IdFKTO, tblGeraet.Id_Geraet);";
using (sqlCommand = new SqlCommand(strQueryRechnung, sqlConnection))
{
sqlCommand.Parameters.Add("#tblFkto.IdFKTO", SqlDbType.Int);
sqlCommand.Parameters.Add("#blGeraet.Id_Geraet", SqlDbType.Int);
sqlCommand.Parameters.Add("#Menge", SqlDbType.Int);
sqlCommand.Parameters.Add("#Einheit", SqlDbType.NVarChar, 50);
sqlCommand.Parameters.Add("#BetragBrutto", SqlDbType.SmallMoney);
sqlCommand.Parameters.Add("#Beginn", SqlDbType.DateTime);
sqlCommand.Parameters.Add("#Ende", SqlDbType.DateTime);
sqlConnection.Open();
for (int i = 2; i < dgvCSVRechnung.Rows.Count; i++)
{
sqlCommand.Parameters["#FKTO"].Value = dgvCSVRechnung.Rows[i].Cells[0].Value;
sqlCommand.Parameters["#Bezeichnung"].Value = dgvCSVRechnung.Rows[i].Cells[2].Value;
sqlCommand.Parameters["#Menge"].Value = Int32.Parse((string)dgvCSVRechnung.Rows[i].Cells[3].Value);
sqlCommand.Parameters["#Einheit"].Value = dgvCSVRechnung.Rows[i].Cells[4].Value;
sqlCommand.Parameters["#BetragBrutto"].Value = Decimal.Parse((string)dgvCSVRechnung.Rows[i].Cells[5].Value);
sqlCommand.Parameters["#Beginn"].Value = DateTime.ParseExact(dgvCSVRechnung.Rows[i].Cells[6].Value.ToString(), "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture);
sqlCommand.Parameters["#Ende"].Value = DateTime.ParseExact(dgvCSVRechnung.Rows[i].Cells[7].Value.ToString(), "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture);
sqlCommand.ExecuteNonQuery();
}
}
sqlConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Fehler!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
So I created a new column named "seatNumber" but it won't show in the Datagridview.
But the rest of the data are showing and is updating except for the new column.
I have here a link of the video just in case it can help. https://youtu.be/adsT7h2uh48
Here is the code of Book Reservation Button:
private void reservationButton_Click(object sender, EventArgs e)
{
//Reservation Button.
string nameString = nameTextbox.Text;
string mobileString = mobileTextbox.Text;
string timeString = timeComboBox.Text;
string seatNumberString = textBox1.Text;
bool allPopulatedBool = nameString != string.Empty && mobileString != string.Empty && timeString != string.Empty && seatNumberString != string.Empty;
if (allPopulatedBool)
{
//if the Form are completed.
SqlConnection con = new SqlConnection("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=LocalDB;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
con.Open();
string queryString = "INSERT INTO CustomersInfo VALUES(#CustomersName, #CustomersMobile, #CustomersTime, #seatNumber)";
SqlParameter param1 = new SqlParameter();
param1.ParameterName = "#CustomersName";
param1.Value = nameString;
SqlParameter param2 = new SqlParameter();
param2.ParameterName = "#CustomersMobile";
param2.Value = mobileString;
SqlParameter param3 = new SqlParameter();
param3.ParameterName = "#CustomersTime";
param3.Value = timeString;
SqlParameter param4 = new SqlParameter();
param4.ParameterName = "#seatNumber";
param4.Value = seatNumberString;
SqlCommand command = new SqlCommand(queryString, con);
command.Parameters.Add(param1);
command.Parameters.Add(param2);
command.Parameters.Add(param3);
command.Parameters.Add(param4);
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("Reservation has been Successfully Booked!", "Schedule Added", MessageBoxButtons.OK, MessageBoxIcon.Information);
nameTextbox.Text = string.Empty;
mobileTextbox.Text = string.Empty;
timeComboBox.Text = string.Empty;
textBox1.Text = string.Empty;
}
if (!allPopulatedBool)
{
//if the Form are not completed.
MessageBox.Show("Please fill out all fields.", "Incomplete Entry", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Unfortunately I can't comment but have to post this as an answer; Did you update the binding/data source as well? Seems the column does appear in the DataGridView, your problem is that no data is displaying, which usually points to the binding/data source (SQL) not having that column in it's output and binding correctly.
Also did you actually assign data to the seatNumber field when you accepted the booking? I saw you select the seat 4 but that doesn't mean it's in the data.
I am inserting data from datagridview into database , I debug my code and found the error Input string was not in a correct format. in the following line
Convert.ToInt32(dgvResult.Rows[i].Cells[9].Value.ToString())
this column is an integer column and when i replaced this line with integer value for example number 3 insert completed without errors , and the other integer columns also inserted same way without any error
this is my code :
if (checkApproveResult.Checked == false && chkupdateApproved.Checked == false)
{
for (int i = 0; i < dgvResult.Rows.Count; i++)
{
result.UPDATE_LAB_RESULTS(Convert.ToInt32(txtOrder.Text),
dgvResult.Rows[i].Cells[7].Value.ToString(),
5,
dgvResult.Rows[i].Cells[6].Value.ToString(),
txtExamUser.Text,
DateTime.Parse(DateTimeExamined.Value.ToString()),
Convert.ToInt32(dgvResult.Rows[i].Cells[2].Value),
dgvResult.Rows[i].Cells[4].Value.ToString(),
dgvResult.Rows[i].Cells[5].Value.ToString(),
Convert.ToInt32(dgvResult.Rows[i].Cells[9].Value.ToString()),
Convert.ToInt32(txtPno.Text),
Convert.ToInt32(txtcustid.Text),
txtReqForm.Text,
dgvResult.Rows[i].Cells[1].Value.ToString(),
Convert.ToInt32(dgvResult.Rows[i].Cells[8].Value.ToString()));
}
MessageBox.Show("Result Saved Successfully ", "Entering Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if (chkupdateApproved.Checked == true)
{
for (int i = 0; i < dgvResult.Rows.Count; i++)
{
result.ADD_LAB_RESULTS_UPDATES(Convert.ToInt32(txtsampleid.Text),
Convert.ToInt32(txtOrder.Text),
Convert.ToInt32(dgvResult.Rows[i].Cells[2].Value),
Convert.ToInt32(txtgroupid.Text),
"YES",
6,
dgvResult.Rows[i].Cells[11].Value.ToString(),
DateTime.Parse(DateTimeExamined.Value.ToString()),
dgvResult.Rows[i].Cells[13].Value.ToString(),
DateTime.Parse(dateTimeApprove.Value.ToString()),
dgvResult.Rows[i].Cells[4].Value.ToString(),
dgvResult.Rows[i].Cells[5].Value.ToString(),
dgvResult.Rows[i].Cells[6].Value.ToString(),
Convert.ToInt32(txtpackageid.Text),
Convert.ToInt32(dgvResult.Rows[i].Cells[9].Value.ToString()),
2,
Convert.ToInt32(txtPno.Text),
Convert.ToInt32(txtcustid.Text), txtReqForm.Text,
Convert.ToInt32(dgvResult.Rows[i].Cells[8].Value.ToString()),
txtupdatedby.Text,
DateTime.Parse(dateupdate.Value.ToString()));
}
update.UPDATE_LAB_RESULT_STATUS(Convert.ToInt32(txtOrder.Text), Convert.ToInt32(txtsampleid.Text), 2);
MessageBox.Show("Result Updated Successfully ", "Update Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
And the code for ADD_LAB_RESULT_UPDATES was :
public void ADD_LAB_RESULTS_UPDATES(int SAMPLE_ID, int ORDER_ID,int TESTID,int GROUPID, string NORMAL_RESULT,
int SAMPLE_STATUS,string EXAMINED_BY,DateTime EXAMINED_DATE, string APPROVED_BY, DateTime APPROVED_DATE,
string RESULT_NUMBER, string RESULT_REPORT, string RESULT_NOTE,int packageid, int machine_id, int deptid,
int patient_no, int custid, string REQ_FORM_NO,int serial,string UPDATED_BY,DateTime UPDATED_DATE)
{
DAL.DataAccessLayer DAL = new DAL.DataAccessLayer();
DAL.open();
SqlParameter[] param = new SqlParameter[22];
param[0] = new SqlParameter("#SAMPLE_ID", SqlDbType.Int);
param[0].Value = SAMPLE_ID;
param[1] = new SqlParameter("#ORDER_ID", SqlDbType.Int);
param[1].Value = ORDER_ID;
param[2] = new SqlParameter("#TESTID", SqlDbType.Int);
param[2].Value = TESTID;
param[3] = new SqlParameter("#GROUPID", SqlDbType.Int);
param[3].Value = GROUPID;
param[4] = new SqlParameter("#NORMAL_RESULT", SqlDbType.VarChar, 10);
param[4].Value = NORMAL_RESULT;
param[5] = new SqlParameter("#SAMPLE_STATUS", SqlDbType.Int);
param[5].Value = SAMPLE_STATUS;
param[6] = new SqlParameter("#EXAMINED_BY", SqlDbType.VarChar, 50);
param[6].Value = EXAMINED_BY;
param[7] = new SqlParameter("#EXAMINED_DATE", SqlDbType.DateTime);
param[7].Value = EXAMINED_DATE;
param[8] = new SqlParameter("#APPROVED_BY", SqlDbType.VarChar, 50);
param[8].Value = APPROVED_BY;
param[9] = new SqlParameter("#APPROVED_DATE", SqlDbType.DateTime);
param[9].Value = APPROVED_DATE;
param[10] = new SqlParameter("#RESULT_NUMBER", SqlDbType.VarChar, 50);
param[10].Value = RESULT_NUMBER;
param[11] = new SqlParameter("#RESULT_REPORT", SqlDbType.VarChar, 2000);
param[11].Value = RESULT_REPORT;
param[12] = new SqlParameter("#RESULT_NOTE", SqlDbType.VarChar, 200);
param[12].Value = RESULT_NOTE;
param[13] = new SqlParameter("#packageid", SqlDbType.Int);
param[13].Value = packageid;
param[14] = new SqlParameter("#machine_id", SqlDbType.Int);
param[14].Value = machine_id;
param[15] = new SqlParameter("#deptid", SqlDbType.Int);
param[15].Value = deptid;
param[16] = new SqlParameter("#patient_no", SqlDbType.Int);
param[16].Value = patient_no;
param[17] = new SqlParameter("#custid", SqlDbType.Int);
param[17].Value = custid;
param[18] = new SqlParameter("#REQ_FORM_NO", SqlDbType.VarChar, 50);
param[18].Value = REQ_FORM_NO;
param[19] = new SqlParameter("#serial", SqlDbType.Int);
param[19].Value = serial;
param[20] = new SqlParameter("#UPDATED_BY", SqlDbType.VarChar, 50);
param[20].Value = UPDATED_BY;
param[21] = new SqlParameter("#UPDATED_DATE", SqlDbType.DateTime);
param[21].Value = UPDATED_DATE;
DAL.ExecuteCommand("ADD_LAB_RESULTS_UPDATES", param);
DAL.close();
}
the error with parameter 14 machine_id
also the table in the database machine_id int.
What is the error ?
More information I have first if statement (update statement)
result. UPDATE_LAB_RESULTS includes same parameter machine_id and its working and inserting without errors.
Second if statement (insert statement) and show the error with machine_id parameter.
You have to check the following :
1- check the parameter list variables types (string , int , ...) and compare it with your procedure you will find one variable type different in the stored procedure integer and in the parameter list string.
I have a problem when executing a SQL Server stored procedure in my application. I've not had this problem before.
My data class is:
public static string conStr
{
get { return ConfigurationManager.ConnectionStrings["conn"].ConnectionString; }
}
public static string Provider
{
get { return ConfigurationManager.ConnectionStrings["conn"].ProviderName; } //Proveedor de DB
}
//DB PROVIDER FACTORY: Objetos de Conexion
public static System.Data.Common.DbProviderFactory dpf
{
get { return DbProviderFactories.GetFactory(Provider); }
}
private static int ejecutaNonQuery(string StoredProcedure, List<DbParameter> parametros)
{//execute nonquery retorna el numero de columnas afectadas en una dB
int Id = 0; //variable para saber cuantos elementos se modificaron despues del ejecutenonquery
try
{
using (DbConnection con = dpf.CreateConnection()) //al usar using la conexion se cerrara automaticamente
{
con.ConnectionString = conStr;
using (DbCommand cmd = dpf.CreateCommand())
{
cmd.Connection = con;
cmd.CommandText = StoredProcedure;
cmd.CommandType = CommandType.StoredProcedure;
foreach (DbParameter param in parametros)
cmd.Parameters.Add(param);
con.Open();
Id = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{ }
return Id;
}
This is the execution:
public int Lotes_Crear_Consolidado(string cliCodigo, string cajCodigo, int cajNumero,
int cajConNumero, string cajConCodigo,
string id1Desde, string id1Hasta,
string id2Desde, string id2Hasta,
string id3Desde, string id3Hasta,
string id4Desde, string id4Hasta,
string id5Desde, string id5Hasta,
string altaPor, string lotEstado,
DateTime fecEmiLot, DateTime fecCadLot)
{
List<DbParameter> paramLotesConsol = new List<DbParameter>();
DbParameter param1 = dpf.CreateParameter();
param1.DbType = DbType.String;
param1.Value = cliCodigo;
param1.ParameterName = "CLIENTE_CODIGO";
paramLotesConsol.Add(param1);
DbParameter param2 = dpf.CreateParameter();
param2.DbType = DbType.String;
param2.Value = cajCodigo;
param2.ParameterName = "CAJA_CODIGO";
paramLotesConsol.Add(param2);
DbParameter param3 = dpf.CreateParameter();
param3.DbType = DbType.Int16;
param3.Value = cajNumero;
param3.ParameterName = "CAJA_NUMERO";
paramLotesConsol.Add(param3);
DbParameter param4 = dpf.CreateParameter();
param4.DbType = DbType.Int16;
param4.Value = cajConNumero;
param4.ParameterName = "CAJA_CONTENIDO_NUMERO";
paramLotesConsol.Add(param4);
DbParameter param5 = dpf.CreateParameter();
param5.DbType = DbType.String;
param5.Value = cajConCodigo;
param5.ParameterName = "CAJA_CONTENIDO_CODIGO";
paramLotesConsol.Add(param5);
DbParameter param6 = dpf.CreateParameter();
param6.DbType = DbType.String;
param6.Value = id1Desde;
param6.ParameterName = "ID1_DESDE";
paramLotesConsol.Add(param6);
DbParameter param7 = dpf.CreateParameter();
param7.DbType = DbType.String;
param7.Value = id1Hasta;
param7.ParameterName = "ID1_HASTA";
paramLotesConsol.Add(param7);
DbParameter param8 = dpf.CreateParameter();
param8.DbType = DbType.String;
param8.Value = id2Desde;
param8.ParameterName = "ID2_DESDE";
paramLotesConsol.Add(param8);
DbParameter param9 = dpf.CreateParameter();
param9.DbType = DbType.String;
param9.Value = id2Hasta;
param9.ParameterName = "ID2_HASTA";
paramLotesConsol.Add(param9);
........
DbParameter param26 = dpf.CreateParameter();
param26.DbType = DbType.String;
param26.Value = altaPor;
param26.ParameterName = "ALTA_POR";
paramLotesConsol.Add(param26);
DbParameter param27 = dpf.CreateParameter();
param27.DbType = DbType.String;
param27.Value = lotEstado;
param27.ParameterName = "ESTADO";
paramLotesConsol.Add(param27);
DbParameter param28 = dpf.CreateParameter();
param28.DbType = DbType.Date;
param28.Value = fecEmiLot;
param28.ParameterName = "FECHA_EMISION_LOTE";
paramLotesConsol.Add(param28);
DbParameter param29 = dpf.CreateParameter();
param29.DbType = DbType.Date;
param29.Value = fecCadLot;
param29.ParameterName = "FECHA_CADUCID_LOTE";
paramLotesConsol.Add(param29);
return ejecutaNonQuery("LOTES_CREAR_CONSOLIDADO", paramLotesConsol);
}
Then I call it like this:
Caja_Contenido_BL loteBL = new Caja_Contenido_BL();
I must insert data from a gridview to my database, so I run on every row the stored procedure for inserting the data.
And the error I get is:
The SqlParameter is already contained by another SqlParameterCollection
Code:
protected void Lotes_Crear_Consolidado(object sender, EventArgs e)
{
string altaPor = User.Identity.Name.ToString().ToUpper();
foreach (GridViewRow grdCajUpd_Row in this.gvwLotConsol_Plant.Rows)
{
string cliCod = Convert.ToString(grdCajUpd_Row.Cells[0].Text);
string cajCod = Convert.ToString(grdCajUpd_Row.Cells[1].Text);
int cajNum = Convert.ToInt16(grdCajUpd_Row.Cells[2].Text);
int cajConNum = Convert.ToInt16(grdCajUpd_Row.Cells[3].Text);
string cajConCod = Convert.ToString(grdCajUpd_Row.Cells[4].Text);
string id1Desde = Convert.ToString(grdCajUpd_Row.Cells[5].Text);
string id1Hasta = Convert.ToString(grdCajUpd_Row.Cells[6].Text);
string id2Desde = Convert.ToString(grdCajUpd_Row.Cells[7].Text);
string id2Hasta = Convert.ToString(grdCajUpd_Row.Cells[8].Text);
string id3Desde = Convert.ToString(grdCajUpd_Row.Cells[9].Text);
string id3Hasta = Convert.ToString(grdCajUpd_Row.Cells[10].Text);
string id4Desde = Convert.ToString(grdCajUpd_Row.Cells[11].Text);
string id4Hasta = Convert.ToString(grdCajUpd_Row.Cells[12].Text);
string id5Desde = Convert.ToString(grdCajUpd_Row.Cells[13].Text);
string id5Hasta = Convert.ToString(grdCajUpd_Row.Cells[14].Text);
string id6Desde = Convert.ToString(grdCajUpd_Row.Cells[15].Text);
string id6Hasta = Convert.ToString(grdCajUpd_Row.Cells[16].Text);
string id7Desde = Convert.ToString(grdCajUpd_Row.Cells[17].Text);
string id7Hasta = Convert.ToString(grdCajUpd_Row.Cells[18].Text);
string id8Desde = Convert.ToString(grdCajUpd_Row.Cells[19].Text);
string id8Hasta = Convert.ToString(grdCajUpd_Row.Cells[20].Text);
string id9Desde = Convert.ToString(grdCajUpd_Row.Cells[21].Text);
string id9Hasta = Convert.ToString(grdCajUpd_Row.Cells[22].Text);
string id10Desde = Convert.ToString(grdCajUpd_Row.Cells[23].Text);
string id10Hasta = Convert.ToString(grdCajUpd_Row.Cells[24].Text);
string estado = Convert.ToString(grdCajUpd_Row.Cells[25].Text);
DateTime fecEmiLot = Convert.ToDateTime(grdCajUpd_Row.Cells[26].Text);
DateTime fecCadLot = Convert.ToDateTime(grdCajUpd_Row.Cells[27].Text);
loteBL.Lotes_Crear_Consolidado(cliCod, cajCod, cajNum, cajConNum, cajConCod,
id1Desde, id1Hasta, id2Desde, id2Hasta, id3Desde, id3Hasta, id4Desde, id4Hasta,
id5Desde, id5Hasta, id6Desde, id6Hasta, id7Desde, id7Hasta, id8Desde, id8Hasta,
id9Desde, id9Hasta, id10Desde, id10Hasta, altaPor, estado, fecEmiLot, fecCadLot);
}
Page.ClientScript.RegisterStartupScript(this.GetType(), "AlertScript", "alert('Lote(s) Creado(s)!');", true);
}
I clear command parameters with cmd.Parameters.Clear().
In SQL Server, I use the same name in SQL parameters for other stored procedures.
I don't know what the problem could be.
Please, if anyone can help me, I wold be grateful
Best regards
You can only use a SqlParameter once. Since you're passing SqlParameters into the method, I assume they are also used somewhere else?
If you wish to keep your call signature and want a quick fix, try this. Instead of
foreach (DbParameter param in parametros)
cmd.Parameters.Add(param);
Try
foreach (ICloneable param in parametros)
cmd.Parameters.Add(param.Clone() as SqlParameter);
If I recall correctly, you need to edit the post in order to delete it. To avoid this sort of issue, I would recommend creating a helper function like this:
private void AddParameter(DbProviderFactory dpf, List<DbParameter> params, DbType type, object value, string name)
{
DbParameter param = dpf.CreateParameter();
param.DbType = type;
param.Value = value;
param.ParameterName = name;
params.Add(param);
}
Then call it like this:
AddParameter(dpf, paramLotesConsol, DbType.String, cliCodigo, "CLIENTE_CODIGO");
AddParameter(dpf, paramLotesConsol, DbType.String, cajCodigo, "CAJA_CODIGO");
// etc.
Thanks guys for helping.
It was my mistake, I'm handling almost 30 parameters, one of them was duplicate.
When i step through the code the parameter is being added, its just when the sql command is executed, it throws this error up
public static DataTable GetPostings2(string AssetNumberV, string PeriodFromV, string PeriodToV)
{
DataTable dtGetPostings2;
try
{
dtGetPostings2 = new DataTable("GetPostings");
SqlParameter AssetNumber = new SqlParameter("#AssetNumber", SqlDbType.VarChar, 6);
AssetNumber.Value = AssetNumberV;
SqlParameter PeriodFrom = new SqlParameter("#PeriodFrom", SqlDbType.VarChar, 6);
PeriodFrom.Value = PeriodFromV;
SqlParameter PeriodTo = new SqlParameter("#PeriodTo", SqlDbType.VarChar, 6);
PeriodTo.Value = PeriodToV;
SqlCommand scGetPostings2 = new SqlCommand("SELECT * FROM [POSTING] WHERE [ASSET_NO] = #AssetNumber And PERIOD >= #PeriodFrom AND PERIOD <= #PeriodTo ORDER by PERIOD, JOUR_REF, JOUR_LINE", DataAccess.AssetConnection);
SqlDataAdapter sdaGetPostings2 = new SqlDataAdapter();
sdaGetPostings2.SelectCommand = scGetPostings2;
sdaGetPostings2.Fill(dtGetPostings2);
return dtGetPostings2;
}
catch (Exception ex)
{
MessageBox.Show("Error Retriving Posting Details: Processed with this error:" + ex.Message);
return null;
}
}
The code listed does not add the parameters to the SqlCommand.Parameters collection. For example:
SqlCommand scGetPostings2 = new SqlCommand("SELECT * FROM [POSTING] WHERE [ASSET_NO] = #AssetNumber And PERIOD >= #PeriodFrom AND PERIOD <= #PeriodTo ORDER by PERIOD, JOUR_REF, JOUR_LINE", DataAccess.AssetConnection);
scGetPostings2.Parameters.Add(AssetNumber);
scGetPostings2.Parameters.Add(PeriodFrom );
scGetPostings2.Parameters.Add(PeriodTo );
// Code continues as above
SqlDataAdapter sdaGetPostings2 = new SqlDataAdapter();
// And so on