grid view updation error - c#

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.

Related

ASP.NET C# Web Form

This is the error
Exception Details: System.InvalidCastException: Object must implement IConvertible.
This is the code that I have, and I am tryin to solve this error for about 5 hours.
I don't know if it's something about the type of the values.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection sqlConnection = new SqlConnection(SqlDataSourceAutovehicule.ConnectionString);
sqlConnection.Open();
SqlCommand sqlCommand = new SqlCommand("INSERT INTO Autovehicul(Marca, Model, Stoc, Categorie) VALUES (" +
"#marca, #model, #stoc, #categorie)", sqlConnection);
SqlParameter pMarca = new SqlParameter("#marca", SqlDbType.VarChar, 50);
pMarca.Value = txtMarca.Text;
SqlParameter pModel = new SqlParameter("#model", SqlDbType.VarChar, 50);
pModel.Value = txtModel.Text;
SqlParameter pStoc = new SqlParameter("#stoc", SqlDbType.Int, 50);
pStoc.Value = txtStoc.Text;
SqlParameter pCategorie = new SqlParameter("#categorie", SqlDbType.Int, 50);
pCategorie.Value = DropDownList1.SelectedValue;
sqlCommand.Parameters.Add(pMarca);
sqlCommand.Parameters.Add(pModel);
sqlCommand.Parameters.Add(pStoc);
sqlCommand.Parameters.Add(pCategorie);
if (sqlCommand.ExecuteNonQuery() > 0)
{
Label1.Text = "adaugare reusita";
GridView1.DataBind();
}
else
{
Label1.Text = "adaugare nereusita";
}
}
A few things?
You don't have 50 digit long integer, so you can dump the optional ,50) for those parmamters.
Also, it looks like your combo box if not selected, is probably returning a "" (empty string). While that can be shoved into a paramter, when it evaluates, it can't convert to a 0.
So, I suggest this:
SqlParameter pCategorie = new SqlParameter("#categorie", SqlDbType.Int);
if (DropDownList1.SelectedValue == "")
pCategorie.Value = 0;
else
pCategorie.Value = DropDownList1SelectedValue;
So, you might want to check tht combo box for null, or a "", but that conversion is failing. And you not see the fail until the execute command.
And the same goes for your text boxes - if they ahve "" (no value, then you need to pass zero.
So, say like this:
using (SqlConnection conn = new SqlConnection(""))
{
using (SqlCommand cmdSQL = new SqlCommand(
"INSERT INTO Autovehicul (Marca, Model, Stoc, Categorie) " +
"VALUES (#marca, #model, #stoc, #categorie", conn))
{
conn.Open();
cmdSQL.Parameters.Add("#marca", SqlDbType.VarChar).Value = txtMarca.Text;
cmdSQL.Parameters.Add("#model", SqlDbType.VarChar).Value = txtModel.Text;
if (if txtSToc.Text == "")
txtStoc.Text = 0;
cmdSQL.Parameters.Add("#stoc", SqlDbType.Int, 50).Value = txtStoc.Text;
if (DropDrownList1.SelectedValue == "")
cmdSQL.Parameters.Add("#categorie", SqlDbType.Int).Value = 0;
else
cmdSQL.Parameters.Add("#categorie", SqlDbType.Int).Value = DropDownList1.SelectedValue;
if (cmdSQL.ExecuteNonQuery() > 0)

Calling a PL_SQL function from inside c#

I have created a PL/SQL function and stored it in my oracle database.Now I want to call that function on clicking a button.
I am using visual studio and c#.
My humble attempt-
private void button3_Click(object sender, EventArgs e)
{
comm = new OracleCommand();
comm.CommandType = CommandType.StoredProcedure;
comm.Connection = conn;
String x1 = textBox1.Text;
String x2 = textBox2.Text;
comm.CommandText = "log_in";
comm.Parameters.Add(new OracleParameter("c", OracleDbType.Varchar2, textBox1.Text, ParameterDirection.Input));
comm.Parameters.Add(new OracleParameter("tt", OracleDbType.Varchar2, 256, ParameterDirection.ReturnValue));
String z = comm.Parameters["z"].Value.ToString();
comm.ExecuteNonQuery();
if (z.Equals('1'))
{ MessageBox.Show("correct"); }
conn.Close();
}
PL/SQL-
CREATE OR REPLACE FUNCTION log_in
(
x IN VARCHAR2,
y IN VARCHAR2
) RETURN VARCHAR2 AS
match_count NUMBER;
BEGIN
SELECT COUNT(*)
INTO match_count
FROM student_login
WHERE email = x
AND password = y;
IF match_count = 0 THEN
RETURN 0;
ELSE
RETURN 1;
END IF;
END;
note-my data source is .NET framework data provider for oracle and the answer is for odp.net
Your function has two input parameters, thus your call must also define two input parameter plus the return parameter. Method Add(OracleParameter) is possible but redundant.
It should be like this:
comm = new OracleCommand();
comm.CommandType = CommandType.StoredProcedure;
comm.Connection = conn;
comm.CommandText = "log_in";
comm.Parameters.Add("x", OracleDbType.Varchar2, ParameterDirection.Input).Value = textBox1.Text;
// As far as I remember "ParameterDirection.Input" is the default, so you may skip it
comm.Parameters.Add("y", OracleDbType.Varchar2, ParameterDirection.Input).Value = textBox2.Text;
comm.Parameters.Add("ret", OracleDbType.Byte, ParameterDirection.ReturnValue);
comm.Parameters["ret"].DbType = DbType.Byte;
comm.ExecuteNonQuery();
String returnValue = comm.Parameters["ret"].Value.ToString();
Actually I never used CommandType.StoredProcedure. If the code above does not work try this one instead:
comm.CommandType = CommandType.Text;
comm.CommandText = "BEGIN :ret := log_in(:x, :y); END;";
Hi I had some problems with StoredProcedure. And finally get it working.
comm = new OracleCommand();
comm.CommandType = CommandType.StoredProcedure;
comm.Connection = conn;
comm.CommandText = "log_in";
// Important is to add returnValue as described bellow
OracleParameter retval = new OracleParameter("ret", OracleDbType.Varchar2 , 20);
retval.Direction = ParameterDirection.ReturnValue;
comm.Parameters.Add(retval);
comm.Parameters.Add("x", OracleDbType.Varchar2, ParameterDirection.Input).Value = textBox1.Text;
comm.Parameters.Add("y", OracleDbType.Varchar2, ParameterDirection.Input).Value = textBox2.Text;
comm.ExecuteNonQuery();
String returnValue = comm.Parameters["ret"].Value.ToString();

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();
}
}
}

Update table record from sqlcommand

I have this situation: in DataEntryForm I have a dropdownlist, where user selects a letter number, and according to that inserts other related data.
I plan to change letter's status in other table by choosing in dropdownlist automatically.
I am using this code:
SqlParameter answertoparam = new SqlParameter("answerto", ansTo);
string commandText = "update IncomeLetters set IncomeLetters.docState_ID ='2' where income_number=('" + ansTo + "' )";
SqlCommand findincomelett = new SqlCommand(commandText, conn);
comm.Parameters.Add(answertoparam);
conn.Open();
findincomelett.ExecuteNonQuery();
comm.ExecuteNonQuery();
Unfortunately, the result is nothing.
Server is not giving error, and it simply refreshes the page that is it.
In your posted code, you are passing the SqlParameter as well as passing the value as raw data. Do either of one and preferably pass it as SqlParameter like
SqlParameter answertoparam = new SqlParameter("answertoparam", ansTo);
string commandText = "update IncomeLetters set IncomeLetters.docState_ID = '2' where income_number = #answertoparam";
SqlCommand findincomelett = new SqlCommand(commandText, conn);
findincomelett.Parameters.Add(answertoparam);
conn.Open();
findincomelett.ExecuteNonQuery();
Moreover, you have two SqlCommand object in place and calling two ExecuteNonQuery() on them. correct that ... see below
SqlCommand findincomelett = new SqlCommand(commandText, conn); --1
comm.Parameters.Add(answertoparam); --2
conn.Open();
findincomelett.ExecuteNonQuery(); --1
comm.ExecuteNonQuery(); --2
As far as I understand, the issue is that the correct IncomeLetters.docState_ID is not updated to '2'.
You may want to debug and see what value you are getting in :
string ansTo = ddlAnswerTo.SelectedItem.Value;
The record in the database that you are expecting to be updated may not have the record that satisfies the where clause 'income_number = #answertoparam'
I would like to bring you here full code of the page.
Idea is: I have page for enrollment. I am passing data to DB through stored procedure (DataInserter).
Problem is here: during enrollment, user selects from dropdownlist number of the letter he would like to answer to, and in the end, the status of the letter on other table of DB (IncomeLetters.tbl), would change from "pending"('1') to "issued" ('2').
I guess, I could clear my point to you and thank you for your support!
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MaktubhoConnectionString2"].ConnectionString);
using (SqlCommand comm = new SqlCommand("DataInserter", conn))
{
comm.CommandType = CommandType.StoredProcedure;
comm.Connection = conn;
SqlParameter employeeparam = new SqlParameter("EmployeeSentIndex", int.Parse(ddlemployee.SelectedItem.Value));
SqlParameter doctypeparam = new SqlParameter("doctype_ID", int.Parse(ddldoctype.SelectedItem.Value));
SqlParameter doccharparam = new SqlParameter("docchar_ID", int.Parse(ddldocchar.SelectedItem.Value));
SqlParameter authorityparam = new SqlParameter("authority", txtauthority.Text);
SqlParameter subjectparam = new SqlParameter("subject", txtsubject.Text);
DateTime dt = DateTime.Now;
string todasdate = dt.ToString("d", CultureInfo.CreateSpecificCulture("de-DE"));
SqlParameter entrydateparam = new SqlParameter("entrydate", todasdate);
string Pathname = "UploadImages/" + Path.GetFileName(FileUpload1.PostedFile.FileName);
SqlParameter imagepathparam = new SqlParameter("image_path", Pathname);
SqlParameter loginparam = new SqlParameter("login", "jsomon");
comm.Parameters.Add(employeeparam);
comm.Parameters.Add(doctypeparam);
comm.Parameters.Add(doccharparam);
comm.Parameters.Add(authorityparam);
comm.Parameters.Add(subjectparam);
comm.Parameters.Add(entrydateparam);
comm.Parameters.Add(imagepathparam);
comm.Parameters.Add(loginparam);
comm.Parameters.Add("#forlabel", SqlDbType.VarChar, 100);
comm.Parameters["#forlabel"].Direction = ParameterDirection.Output;
FileUpload1.SaveAs(Server.MapPath("~/UploadImages/" + FileUpload1.FileName));
string ansTo = ddlAnswerTo.SelectedItem.Value;
SqlParameter answertoparam = new SqlParameter("answertoparam", ansTo);
string commandText = "update IncomeLetters set IncomeLetters.docState_ID = '2' where income_number = #answertoparam";
SqlCommand findincomelett = new SqlCommand(commandText, conn);
findincomelett.Parameters.Add(answertoparam);
conn.Open();
findincomelett.ExecuteNonQuery();
comm.ExecuteNonQuery();
lblresult.Visible = true;
Image1.Visible = true;
lblresult.Text = "Document number:";
lblnumber.Visible = true;
lblnumber.Text = (string)comm.Parameters["#forlabel"].Value; ;
conn.Close();
}
txtauthority.Text = "";
txtsubject.Text = "";
}

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.

Categories