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.
Related
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();
}
}
}
I'm having to select, update, delete, etc. basically everywhere on my web application and every time I'm having to write something like this:
con.Open();
cmd = new SqlCommand("update items set item_cost = #cost, item_retail_value = #retail, item_v_style = #v_style, item_v_color = #v_color, item_description = #description, " +
"item_date_modify = #date, item_time_modify = #time, item_user_modify = #user where item_style = #style and item_color = #color and item_sec_dimenssion = #sec", con);
cmd.Parameters.Add("#style", SqlDbType.VarChar, 15).Value = styl;
cmd.Parameters.Add("#color", SqlDbType.VarChar, 3).Value = colr;
cmd.Parameters.Add("#sec", SqlDbType.VarChar, 8).Value = sdim;
cmd.Parameters.Add("#size", SqlDbType.VarChar, 3).Value = size;
cmd.Parameters.Add("#cost", SqlDbType.VarChar, 8).Value = sprice;
cmd.Parameters.Add("#retail", SqlDbType.VarChar, 8).Value = sretail;
cmd.Parameters.Add("#uom", SqlDbType.VarChar, 3).Value = uom;
cmd.Parameters.Add("#sku", SqlDbType.VarChar, 10).Value = sku;
cmd.Parameters.Add("#barcode", SqlDbType.VarChar, 20).Value = barcode;
cmd.Parameters.Add("#v_style", SqlDbType.VarChar, 100).Value = v_style;
cmd.Parameters.Add("#v_color", SqlDbType.VarChar, 20).Value = v_color;
cmd.Parameters.Add("#description", SqlDbType.VarChar, 40).Value = description;
cmd.Parameters.Add("#date", SqlDbType.VarChar, 20).Value = date;
cmd.Parameters.Add("#time", SqlDbType.VarChar, 20).Value = time;
cmd.Parameters.Add("#user", SqlDbType.VarChar, 20).Value = user;
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
Is there a way to create a Class to create SqlConnection with a SqlCommand for "Select", "Update", "Delete", etc. and just provide the table, the fields, parameters and the criteria so I don't have to write all this code every time.
Any help will really appreciate it.
Linq2Sql
Entity Framework
nHibernate
Dapper
BLToolkit
create a class with Singleton and then every time you want to do anything with SqlConnection
you can use the same object.
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
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.
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.