C# stored procedure with parameters - c#

I am receiving an error in my application and i can not figure out how to resolve it. Here is the code:
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
myConnection.Open();
SqlCommand cmd = new SqlCommand("SELECT ServerIP FROM Servers", myConnection);
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
string serverIP = rdr["ServerIP"].ToString();
ScheduledTasks st = new ScheduledTasks(#"\\" + serverIP);
string[] taskNames = st.GetTaskNames();
foreach (string name in taskNames)
{
Task t = st.OpenTask(name);
var status = t.Status;
var recentRun = t.MostRecentRunTime;
var nextRun = t.NextRunTime;
var appName = t.ApplicationName;
SqlConnection myConnection2 = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
SqlCommand myCommand2 = new SqlCommand("sp_AddScheduledTasks", myConnection2);
try
{
myConnection2.Open();
myCommand2.CommandType = CommandType.StoredProcedure;
myCommand2.Parameters.Add("#ID", SqlDbType.Int);
myCommand2.Parameters["#ID"].Direction = ParameterDirection.Output;
myCommand2.Parameters.Add("#ServerIP", SqlDbType.NVarChar, 20).Value = serverIP;
myCommand2.Parameters.Add("#TaskName", SqlDbType.NVarChar, 50).Value = t;
myCommand2.Parameters.Add("#MostRecentRun", SqlDbType.DateTime).Value = recentRun;
myCommand2.Parameters.Add("#NextRunTime", SqlDbType.DateTime).Value = nextRun;
myCommand2.Parameters.Add("#AppName", SqlDbType.NVarChar, 50).Value = appName;
myCommand2.Parameters.Add("#Status", SqlDbType.NVarChar, 50).Value = status;
int rows = myCommand2.ExecuteNonQuery();
}
finally
{
myConnection2.Close();
}
The error I am receiving is with the ExecuteNonQuery. It says
InvalidCastException Failed to
convert parameter value from a Task to
a String.
I thought it had something to do with where I put the try (inside the if statement) but I am not sure. Any help would be much appreciated.
Thanks,
Matt

My guess is that in
myCommand2.Parameters.Add("#TaskName", SqlDbType.NVarChar, 50).Value = t;
t is not a string?

t is of type Task but when you pass it to your stored procedure you are passing it as nvarchar.
Here is your code:
myCommand2.Parameters.Add("#TaskName", SqlDbType.NVarChar, 50).Value = t;

Assuming your name variable is indeed the #TaskName simply use name
myCommand2.Parameters.Add("#TaskName", SqlDbType.NVarChar, 50).Value = name;
or if you override ToString()
myCommand2.Parameters.Add("#TaskName", SqlDbType.NVarChar, 50).Value = t.ToString();
or if you have Name on your Task object
myCommand2.Parameters.Add("#TaskName", SqlDbType.NVarChar, 50).Value = t.Name;

In the line:
myCommand2.Parameters.Add("#TaskName", SqlDbType.NVarChar, 50).Value = t;
I think you have to pass t.Name or t.ToString() up on the task's name (I don't know it).

I think the problem is with this line:
myCommand2.Parameters.Add("#TaskName", SqlDbType.NVarChar, 50).Value = t;
t cannot be converted to a string. You could try t.Name or t.ToString() (not sure what properties are available on that class off the top of my head.)

T is type of Task and and ado try convert it to string
you should put t.GetType().Name or the real task name here
because we can't pass objects as parameter the only type are known sqltypes

myCommand2.Parameters.Add("#TaskName", SqlDbType.NVarChar, 50).Value = t;
t is a Task not a string. This should probably by name.

On the line:
myCommand2.Parameters.Add("#TaskName", SqlDbType.NVarChar, 50).Value = t;
't' is a task, not a string. You need to get the task name instead (by the looks of it)

The issue is on this line:
myCommand2.Parameters.Add("#TaskName", SqlDbType.NVarChar, 50).Value = t;
You are passing the task object in instead of the name of the task.

Related

No Mapping Exists from Object Type System.Widows.Forms.DataGridViewTextBoxCell

I'm new to C# coding and this website so bear with me. On the button click I want my stored procedure to execute and populate the datagridview. When I run the application and click the button I keep getting an error saying:
"No mapping exists from object type System.Windows.Forms.DataGridViewTextBoxCell to a known managed provider native type."
How do I fix this? I've tried converting the parameters to their data types which doesn't seem to work either. I've been stuck on this for a while and am struggling to find anything on the internet about my specific error. Thank you.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection sqlcn1 = new SqlConnection("My Server Connection String");
sqlcn1.Open();
//Stored Procedure
SqlCommand sqlcmddel = new SqlCommand("My_Stored_Procedure", sqlcn1);
sqlcmddel.CommandType = CommandType.StoredProcedure;
sqlcmddel.ExecuteNonQuery();
sqlcn1 = new SqlConnection("My Server Connection String");
sqlcn1.Open();
foreach (DataGridViewRow row in dataGridView1.Rows) ;
SqlCommand sqlcmdins = new SqlCommand("My_Stored_Procedure", sqlcn1);
//Stored Procedure
sqlcmdins.CommandType = CommandType.StoredProcedure;
sqlcmdins.Parameters.Add("#sugnum", SqlDbType.Int).Value = dataGridView1.Rows[Ournum].Cells[0];
sqlcmdins.Parameters.Add("#sugtype", SqlDbType.NVarChar, 50).Value = dataGridView1.Rows[Ournum].Cells[1];
sqlcmdins.Parameters.Add("#buyerid", SqlDbType.NVarChar, 50).Value = dataGridView1.Rows[Ournum].Cells[2];
sqlcmdins.Parameters.Add("#duedate", SqlDbType.DateTime).Value = dataGridView1.Rows[Ournum].Cells[3];
sqlcmdins.Parameters.Add("#xrelqty", SqlDbType.Float).Value = dataGridView1.Rows[Ournum].Cells[4];
sqlcmdins.Parameters.Add("#purchasingfactor", SqlDbType.Float).Value = dataGridView1.Rows[Ournum].Cells[5];
sqlcmdins.Parameters.Add("#relqty", SqlDbType.Float).Value = dataGridView1.Rows[Ournum].Cells[6];
sqlcmdins.Parameters.Add("#jobnum", SqlDbType.NVarChar, 20).Value = dataGridView1.Rows[Ournum].Cells[7];
sqlcmdins.Parameters.Add("#assemblyseq", SqlDbType.SmallInt).Value = dataGridView1.Rows[Ournum].Cells[8];
sqlcmdins.Parameters.Add("#jobseq", SqlDbType.SmallInt).Value = dataGridView1.Rows[Ournum].Cells[9];
sqlcmdins.Parameters.Add("#warehousecode", SqlDbType.NVarChar, 50).Value = dataGridView1.Rows[Ournum].Cells[10];
sqlcmdins.Parameters.Add("#fob", SqlDbType.NVarChar, 50).Value = dataGridView1.Rows[Ournum].Cells[11];
sqlcmdins.Parameters.Add("#shipviacode", SqlDbType.NVarChar, 50).Value = dataGridView1.Rows[Ournum].Cells[12];
sqlcmdins.Parameters.Add("#termscode", SqlDbType.NVarChar, 50).Value = dataGridView1.Rows[Ournum].Cells[13];
sqlcmdins.Parameters.Add("#vendornum", SqlDbType.Int).Value = dataGridView1.Rows[Ournum].Cells[14];
sqlcmdins.Parameters.Add("#purpoint", SqlDbType.Int).Value = dataGridView1.Rows[Ournum].Cells[15];
sqlcmdins.Parameters.Add("#linedesc", SqlDbType.NVarChar, 50).Value = dataGridView1.Rows[Ournum].Cells[16];
sqlcmdins.Parameters.Add("#ium", SqlDbType.NVarChar, 10).Value = dataGridView1.Rows[Ournum].Cells[17];
sqlcmdins.Parameters.Add("#unitprice", SqlDbType.Float).Value = dataGridView1.Rows[Ournum].Cells[18];
sqlcmdins.Parameters.Add("#docunitprice", SqlDbType.Float).Value = dataGridView1.Rows[Ournum].Cells[19];
sqlcmdins.Parameters.Add("#taxable", SqlDbType.Bit).Value = dataGridView1.Rows[Ournum].Cells[20];
Your issue is that you're trying to pass the Cell into the stored procedure. You need to pass in the cells value.
Also, because you've put a ';' at the end of the foreach call, your loop around the rows isn't doing anything. Assuming you're trying to insert all the rows from the datagridview, you'll need something like this...
using (SqlConnection sqlcn1 = new SqlConnection("My Server Connection String"))
{
sqlcn1.Open();
//Stored Procedure
using (SqlCommand sqlcmddel = new SqlCommand("My_Stored_Procedure", sqlcn1))
{
sqlcmddel.CommandType = CommandType.StoredProcedure;
sqlcmddel.ExecuteNonQuery();
}
foreach (DataGridViewRow row in dataGridView1.Rows)
{
using (SqlCommand sqlcmdins = new SqlCommand("My_Stored_Procedure", sqlcn1))
{
sqlcmdins.CommandType = CommandType.StoredProcedure;
//Stored Procedure
sqlcmdins.Parameters.Add("#sugnum", SqlDbType.Int).Value = row.Cells[0].Value;
sqlcmdins.Parameters.Add("#sugtype", SqlDbType.NVarChar, 50).Value = row.Cells[1].Value;
sqlcmdins.Parameters.Add("#buyerid", SqlDbType.NVarChar, 50).Value = row.Cells[2].Value;
sqlcmdins.Parameters.Add("#duedate", SqlDbType.DateTime).Value = row.Cells[3].Value;
sqlcmdins.Parameters.Add("#xrelqty", SqlDbType.Float).Value = row.Cells[4].Value;
sqlcmdins.Parameters.Add("#purchasingfactor", SqlDbType.Float).Value = row.Cells[5].Value;
sqlcmdins.Parameters.Add("#relqty", SqlDbType.Float).Value = row.Cells[6].Value;
sqlcmdins.Parameters.Add("#jobnum", SqlDbType.NVarChar, 20).Value = row.Cells[7].Value;
sqlcmdins.Parameters.Add("#assemblyseq", SqlDbType.SmallInt).Value = row.Cells[8].Value;
sqlcmdins.Parameters.Add("#jobseq", SqlDbType.SmallInt).Value = row.Cells[9].Value;
sqlcmdins.Parameters.Add("#warehousecode", SqlDbType.NVarChar, 50).Value = row.Cells[10].Value;
sqlcmdins.Parameters.Add("#fob", SqlDbType.NVarChar, 50).Value = row.Cells[11].Value;
sqlcmdins.Parameters.Add("#shipviacode", SqlDbType.NVarChar, 50).Value = row.Cells[12].Value;
sqlcmdins.Parameters.Add("#termscode", SqlDbType.NVarChar, 50).Value = row.Cells[13].Value;
sqlcmdins.Parameters.Add("#vendornum", SqlDbType.Int).Value = row.Cells[14].Value;
sqlcmdins.Parameters.Add("#purpoint", SqlDbType.Int).Value = row.Cells[15].Value;
sqlcmdins.Parameters.Add("#linedesc", SqlDbType.NVarChar, 50).Value = row.Cells[16].Value;
sqlcmdins.Parameters.Add("#ium", SqlDbType.NVarChar, 10).Value = row.Cells[17].Value;
sqlcmdins.Parameters.Add("#unitprice", SqlDbType.Float).Value = row.Cells[18].Value;
sqlcmdins.Parameters.Add("#docunitprice", SqlDbType.Float).Value = row.Cells[19].Value;
sqlcmdins.Parameters.Add("#taxable", SqlDbType.Bit).Value = row.Cells[20].Value;
sqlcmdins.ExecuteNonQuery();
}
}
}

Invalid Attempt To Read Data when no Data is Present [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Values Not Being Stored to Database
cmd = new SqlCommand("ImportExcel", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#UserCategory", SqlDbType.NVarChar, 100).Value = imp.UserCategory;
cmd.Parameters.Add("#CompanyName", SqlDbType.NVarChar, 200).Value = imp.CompanyName;
cmd.Parameters.Add("#PrimaryContact", SqlDbType.NVarChar, 200).Value = imp.PrimaryContact;
cmd.Parameters.Add("#Title", SqlDbType.NVarChar, 50).Value = imp.Title;
cmd.Parameters.Add("#FirstName", SqlDbType.NVarChar, 100).Value = imp.FirstName;
cmd.Parameters.Add("#LastName", SqlDbType.NVarChar, 100).Value = imp.LastName;
cmd.Parameters.Add("#LeadIndustryType", SqlDbType.NVarChar, 100).Value = imp.IndustruType;
cmd.Parameters.Add("#SupplierService", SqlDbType.NVarChar).Value = imp.ServiceCategory;
cmd.Parameters.Add("#Designation", SqlDbType.NVarChar, 100).Value = imp.Designation;
// cmd.Parameters.Add("#AnnualRevenue", SqlDbType.NVarChar, 50).Value = ContactsObj.AnnualRevenue;
cmd.Parameters.Add("#PhoneCountryCode", SqlDbType.NVarChar, 50).Value = imp.PhoneCountryCode;
cmd.Parameters.Add("#PhoneNumber", SqlDbType.NVarChar, 50).Value = imp.PhoneNumber;
cmd.Parameters.Add("#MobileCountryCode", SqlDbType.NVarChar, 50).Value = imp.MobileCountryCode;
cmd.Parameters.Add("#MobileNumber", SqlDbType.NVarChar, 50).Value = imp.MobileNumber;
cmd.Parameters.Add("#Email", SqlDbType.NVarChar, 200).Value = imp.Email;
if (!String.IsNullOrEmpty(imp.EmailOption))
{
cmd.Parameters.Add("#EmailOption", SqlDbType.Bit).Value = imp.EmailOption;
}
else
{
cmd.Parameters.Add("#EmailOption", SqlDbType.Bit).Value = DBNull.Value;
}
if (!String.IsNullOrEmpty(imp.OfferAlertReceive))
{
cmd.Parameters.Add("#OfferAlertReceive", SqlDbType.Bit).Value = imp.OfferAlertReceive;
}
else
{
cmd.Parameters.Add("#OfferAlertReceive", SqlDbType.Bit).Value = DBNull.Value;
}
//cmd.Parameters.Add("#SecondaryEmail", SqlDbType.NVarChar, 200).Value = imp.SecondaryEmail;
cmd.Parameters.Add("#SkypeID", SqlDbType.NVarChar, 200).Value =imp.SkypeID;
cmd.Parameters.Add("#Fax", SqlDbType.NVarChar, 50).Value = imp.Fax;
cmd.Parameters.Add("#Website", SqlDbType.NVarChar, 200).Value = imp.Website;
cmd.Parameters.Add("#PresentAddressLine1", SqlDbType.NVarChar, 200).Value =imp.PresentAddressLine1;
cmd.Parameters.Add("#PresentAddressLine2", SqlDbType.NVarChar, 200).Value =imp.PresentAddressLine2;
cmd.Parameters.Add("#PresentCity", SqlDbType.NVarChar, 200).Value =imp.PresentCity;
cmd.Parameters.Add("#PresentState", SqlDbType.NVarChar, 100).Value = imp.PresentState;
cmd.Parameters.Add("#PresentCountry", SqlDbType.NVarChar, 100).Value = imp.PresentCountry;
cmd.Parameters.Add("#PresentZipCode", SqlDbType.NVarChar, 50).Value = imp.PresentZipCode;
cmd.Parameters.Add("#PermanentAddressLine1", SqlDbType.NVarChar, 200).Value = imp.PermanentAddressLine1;
cmd.Parameters.Add("#PermanentAddressLine2", SqlDbType.NVarChar, 200).Value = imp.PermanentAddressLine2;
cmd.Parameters.Add("#PermanentCity", SqlDbType.NVarChar, 200).Value = imp.PermanentCity;
cmd.Parameters.Add("#PermanentState", SqlDbType.NVarChar, 100).Value = imp.PermanentState;
if (!String.IsNullOrEmpty(imp.PermanentCountry))
{
cmd.Parameters.Add("#PermanentCountry", SqlDbType.NVarChar, 100).Value = imp.PermanentCountry;
}
else
{
cmd.Parameters.Add("#PermanentCountry", SqlDbType.NVarChar, 100).Value = DBNull.Value;
}
cmd.Parameters.Add("#PermanentZipCode", SqlDbType.NVarChar, 50).Value = imp.PermanentZipCode;
if (!String.IsNullOrEmpty(imp.GroupName))
{
cmd.Parameters.Add("#OfferAlertType", SqlDbType.NVarChar, 100).Value = imp.OfferAlertType;
}
else
{
cmd.Parameters.Add("#OfferAlertType", SqlDbType.NVarChar, 100).Value = DBNull.Value;
}
if (!String.IsNullOrEmpty(imp.GroupName))
{
cmd.Parameters.Add("#GroupName", SqlDbType.NVarChar, 100).Value = imp.GroupName;
}
else
{
cmd.Parameters.Add("#GroupName", SqlDbType.NVarChar, 100).Value = DBNull.Value;
}
cmd.Parameters.Add("#LeadSource",SqlDbType.NVarChar,100).Value=imp.LeadSource;
cmd.Parameters.Add("#Description", SqlDbType.NVarChar, 300).Value = imp.Description;
cmd.Parameters.Add("#CreatedBy", SqlDbType.NVarChar, 100).Value = imp.CreatedBy;
cmd.Parameters.Add("#ip", SqlDbType.NVarChar, 50).Value = imp.ip;
con.Open();
SqlDataReader dr1 = cmd.ExecuteReader();
//dr1 = cmd.ExecuteReader();
string st = string.Empty;
while (dr1.Read())
{
st = dr1[0].ToString();
}
st = dr1[0].ToString();
return st;
Remove this line after your while loop:-
st = dr1[0].ToString();
You need to call the Read() method to actually read the date from DataReader object.
Also, it would be better if you will wrap your code within using block:-
using (SqlDataReader dr1 = cmd.ExecuteReader())
{
while (dr1.Read())
{
st = dr1[0].ToString(); //With Index
st = dr1["ColumnName"].ToString(); //With Column Name
}
}
Update:
Based on your comment, this is an Insert SP and you were trying to read the return value so you can't use SqlDataReader, if you want to return whether SP successfully inserted data, you can return status code like 1 for successfull insertion & 0 for failure or something. You can then read this return code like this:-
SqlParameter returnParameter = cmd.Parameters.Add("StatusCd", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
int statusCode = (int)returnParameter.Value;
But if you want to return a text like you have mentioned Successfully Inserted, you need to add that as Output parameter because SQL can only return interger values, you can then retrieve this output value as:-
SqlParameter output = new SqlParameter("#code", SqlDbType.Int);
output.Direction = ParameterDirection.Output;
cmd.Parameters.Add(output);
cmd.ExecuteNonQuery();
st = output.Value.ToString();
Here, #code will be the ouput parameter in your SP, which you'll set as: SET #code = 'Insert successfull'.

Invalid Cat Exception

I am trying to 'grab' the ID field (PK) from a database after data has been entered to it. Once I get the ID, I want to input it into another table (for relationship purposes). However, my attempts are unsuccessful.
This is what I'm currently doing:
int CompanyID;
SqlConnection con = new SqlConnection("Data Source=******;Initial Catalog= ********");
SqlCommand cmd = con.CreateCommand();
con.Open();
cmd.CommandText = "insert into [Company Information] (Expo_Year, Partnership, Company_Name_Pub, Address_Pub, City_Pub, State_Pub, Zip_Pub, Phone_Pub, Fax_Pub, Email_Pub, Contact_Pub, Company_Name_Ex, Address_Ex, City_Ex, State_Ex, Zip_Ex, Phone_Ex, Fax_Ex, Email_Ex, Contact_Ex) VALUES (#Year, #Partnership,#PubCompanyName,#PubAddress,#PubCity,#PubState,#PubZip,#PubPhone,#PubFax,#PubEmail,#PubContact,#ExCompanyName,#ExAddress,#ExCity,#ExState,#ExZip,#ExPhone,#ExFax,#ExEmail,#ExContact) SELECT SCOPE_IDENTITY();";
SqlParameter param = new SqlParameter();
param.ParameterName = "#PubCompanyName";
param.Value = CompanyNmTxt.Text;
cmd.Parameters.Add("#Year", System.Data.SqlDbType.VarChar, 50).Value = Year.Text;
cmd.Parameters.Add("#Partnership", System.Data.SqlDbType.VarChar, 50).Value = DropDownList1.Text;
cmd.Parameters.Add("#PubCompanyName", System.Data.SqlDbType.VarChar,50).Value = CompanyNmTxt.Text;
cmd.Parameters.Add("#PubAddress", System.Data.SqlDbType.VarChar,50).Value = CompanyAddTxt.Text;
cmd.Parameters.Add("#PubCity", System.Data.SqlDbType.VarChar,50).Value = CompanyCtyTxt.Text;
cmd.Parameters.Add("#PubState", System.Data.SqlDbType.Char,2).Value = StateDD.Text;
cmd.Parameters.Add("#PubZip", System.Data.SqlDbType.Int,8).Value = CompanyZipTxt.Text;
cmd.Parameters.Add("#PubPhone", System.Data.SqlDbType.VarChar,50).Value = CompanyPhoneTxt.Text;
cmd.Parameters.Add("#PubFax", System.Data.SqlDbType.VarChar,50).Value = CompanyFaxTxt.Text;
cmd.Parameters.Add("#PubEmail", System.Data.SqlDbType.VarChar,50).Value = CompanyEmailTxt.Text;
cmd.Parameters.Add("#PubContact", System.Data.SqlDbType.VarChar,50).Value = CompanyContactTxt.Text;
cmd.Parameters.Add("#ExCompanyName", System.Data.SqlDbType.VarChar, 50).Value = ExCompanyNmTxt0.Text;
cmd.Parameters.Add("#ExAddress", System.Data.SqlDbType.VarChar, 50).Value = ExCompanyAddTxt0.Text;
cmd.Parameters.Add("#ExCity", System.Data.SqlDbType.VarChar, 50).Value = ExCompanyCtyTxt0.Text;
cmd.Parameters.Add("#ExState", System.Data.SqlDbType.Char, 2).Value = ExStateDD.Text;
cmd.Parameters.Add("#ExZip", System.Data.SqlDbType.Int, 8).Value = ExCompanyZipTxt0.Text;
cmd.Parameters.Add("#ExPhone", System.Data.SqlDbType.VarChar, 50).Value = ExCompanyPhoneTxt0.Text;
cmd.Parameters.Add("#ExFax", System.Data.SqlDbType.VarChar, 50).Value = ExCompanyFaxTxt0.Text;
cmd.Parameters.Add("#ExEmail", System.Data.SqlDbType.VarChar, 50).Value = ExCompanyEmailTxt0.Text;
cmd.Parameters.Add("#ExContact", System.Data.SqlDbType.VarChar, 50).Value = ExCompanyContactTxt0.Text;
CompanyID = (int)cmd.ExecuteScalar();
con.Close();
I get the error:
InvalidCastException was unhandeled by user code; Specified cast is not valid.
The obvious things that stick out to me are that you're storing zip codes as integers. They really should be strings (since leading zeros are valid). This line might be a culprit:
cmd.Parameters.Add("#PubZip", System.Data.SqlDbType.Int,8).Value = CompanyZipTxt.Text;
You might want to try something along the lines of:
int companyZip;
Int32.TryParse(CompanyZipTxt.Text, out companyZip);
cmd.Parameters.Add("#PubZip", System.Data.SqlDbType.Int, 8).Value = companyZip;
You also have a couple of other lines with similar issues.
From the documentation for ExecuteScalar:
Return Value Type: System.Object The first column of the first row in
the result set, or a null reference (Nothing in Visual Basic) if the
result set is empty. Returns a maximum of 2033 characters.
What's in the first column of your table? (Presumably, it's your CompanyId column.) Is it a uniqueId? That would cast to a Guid, not an int.

Error on Insert SqlCommand in ASP.NET

I'm going crazy here, can someone please tell me what's wrong with this code
con.Open();
cmd = new SqlCommand("INSERT INTO COUNTERS(COUNTER_START, COUNTER_CURRENT, COUNTER_NEXT, COUNTER_TYPE, COUNTER_DATE_CREATED, COUNTER_TIME_CREATED, COUNTER_CREATED_BY) " +
"VALUES(#counter_start, #counter_current, #counter_next, #counter_type, #date, #time, #user)", con);
cmd.Parameters.Add("#counter_start", SqlDbType.Int).Value = counter_start.Text;
cmd.Parameters.Add("#counter_current", SqlDbType.Int).Value = counter_current.Text;
cmd.Parameters.Add("#counter_next", SqlDbType.Int).Value = counter_next.Text;
cmd.Parameters.Add("#counter_type", SqlDbType.VarChar, 10).Value = counter_type.Text;
cmd.Parameters.Add("#date", SqlDbType.VarChar, 20).Value = date;
cmd.Parameters.Add("#time", SqlDbType.VarChar, 20).Value = time;
cmd.Parameters.Add("#user", SqlDbType.VarChar, 50).Value = user;
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
I'm getting this error
The parameterized query '(#counter_start int,#counter_current int,#counter_next int,#coun' expects the parameter '#user', which was
not supplied
Any input will be really appreciate it.
You may try debugging the application and see what value is being held by variable user. I think the user you are supplying is null. If you are using C# 4.0 then try
cmd.Parameters.Add("#user", SqlDbType.VarChar, 50).Value = user ?? DBNull.Value;
or for earlier versions of C#
cmd.Parameters.Add("#user", SqlDbType.VarChar, 50).Value = user != null ? user : DBNull.Value;
You may also use string.Empty in place of DBNull.Value, if you want an empty string instead of DBNull

grid view updation error

this is the coe for my updation in the grid view.
when i execute it the edit command works properly but when i click update this error pops up next to my cmd.ExecuteNonQuery();
"Failed to convert parameter value from a String to a Decimal."
please help me here.if there is another way for me to add the details into the database plz do tell me
thanks in advance. :)
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string v = System.Configuration.ConfigurationManager.ConnectionStrings["harish"].ConnectionString;
con = new OracleConnection(v);
con.Open();
string query = "update leave_module1 set name=:name,desig=:desig,srno=:srno,tol=:tol,compdates=:compdates,fd=:fd,td=:td,noofdays=:nod,remarks=:remarks";
OracleCommand cmd = new OracleCommand(query, con);
cmd.Parameters.Add(":name", OracleType.VarChar, 50).Value = GridView1.Rows[e.RowIndex].Cells[0].Text;
cmd.Parameters.Add(":desig", OracleType.VarChar, 30).Value = GridView1.Rows[e.RowIndex].Cells[1].Text;
cmd.Parameters.Add(":srno", OracleType.Number, 8).Value = GridView1.Rows[e.RowIndex].Cells[2].Text;
cmd.Parameters.Add(":tol", OracleType.VarChar, 10).Value = GridView1.Rows[e.RowIndex].Cells[3].Text;
cmd.Parameters.Add(":compdates", OracleType.VarChar, 30).Value = GridView1.Rows[e.RowIndex].Cells[4].Text;
cmd.Parameters.Add(":fd", OracleType.DateTime).Value = GridView1.Rows[e.RowIndex].Cells[5].Text;
cmd.Parameters.Add(":td", OracleType.DateTime).Value = GridView1.Rows[e.RowIndex].Cells[6].Text;
cmd.Parameters.Add(":nod", OracleType.Number, 3).Value = GridView1.Rows[e.RowIndex].Cells[7].Text;
cmd.Parameters.Add(":remarks", OracleType.VarChar, 50).Value = GridView1.Rows[e.RowIndex].Cells[8].Text;
cmd.ExecuteNonQuery();
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('The Data has been added');window.location='Default2.aspx';</script>;");
cmd.Dispose();
con.Close();
}
Do not precede the named parameter with a colon (:). The .NET Framework Data Provider for Oracle supplies the colon automatically.
Convert parameters to relevant type before assigning to a parameter
cmd.Parameters.Add("name", OracleType.VarChar, 50).Value = GridView1.Rows[e.RowIndex].Cells[0].Text; // this is ok
cmd.Parameters.Add("fd", OracleType.DateTime).Value = Convert.ToDateTime(GridView1.Rows[e.RowIndex].Cells[5].Text);
cmd.Parameters.Add("nod", OracleType.Number, 3).Value = Convert.ToDecimal(GridView1.Rows[e.RowIndex].Cells[7].Text);
Use Using block
here is sample code
using (var connection = new OracleConnection(connectionString))
{
connection.Open();
using (var command = new OracleCommand(queryString, connection))
{
// add parameters here
command.ExecuteNonQuery();
}
}
Convert string to decimal:
cmd.Parameters.Add(":srno", OracleType.Number, 8).Value = Convert.ToDecimal(GridView1.Rows[e.RowIndex].Cells[2].Text);
cmd.Parameters.Add(":nod", OracleType.Number, 3).Value = Convert.ToDecimal(GridView1.Rows[e.RowIndex].Cells[7].Text);
Convert string to datetime:
cmd.Parameters.Add(":fd", OracleType.DateTime).Value = DateTime.Parse(GridView1.Rows[e.RowIndex].Cells[5].Text);
cmd.Parameters.Add(":td", OracleType.DateTime).Value = DateTime.Parse(GridView1.Rows[e.RowIndex].Cells[6].Text);
Before converting, check if the string values are not empty, if any one is empty then assign default decimal / datetime value.

Categories