I've literally searched everything and everywhere but somehow this piece of code of mine just won't work no matter what I've tried.
So I have created a database on a SQL server and linked it, tested it, great it works. OK, so the problem is when I'm trying to insert data on a website textbox and have THAT data copied/transferred into my database table. So I only now get an error saying that 'Exception unhandeld and Must declare the scalar variable "#f_name".
I would appreciate it if anyone can assist? Thanks.
private void Save(string hfname, string hlname, string hemail, string hcomment)
{
SqlConnection myConn = new SqlConnection(GetConnectionString());
String sql = "INSERT INTO helpdesk (First_Name, Last_Name, Email, Comments) VALUES " + " (#f_name, #l_name, #email, #comment)";
SqlCommand cmd = new SqlCommand(sql, myConn);
ITDBDataset itdbDataSet = new ITDBDataset();
SqlDataAdapter dataAdapter;
try
{
myConn.Open();
dataAdapter = new SqlDataAdapter(cmd);
dataAdapter.Fill(itdbDataSet);
myConn.Close();
SqlParameter[] param = new SqlParameter[6];
//para,[0]
param[0] = new SqlParameter("#f_name", System.Data.SqlDbType.VarChar, 50);
param[1] = new SqlParameter("#l_name", System.Data.SqlDbType.VarChar, 50);
param[2] = new SqlParameter("#email", System.Data.SqlDbType.VarChar, 30);
param[3] = new SqlParameter("#comment", System.Data.SqlDbType.VarChar, 600);
param[0].Value = hfname;
param[1].Value = hlname;
param[2].Value = hemail;
param[3].Value = hcomment;
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
//SqlDataReader reader = cmd.ExecuteReader();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Not Added, check context!";
msg += ex.Message;
throw new Exception(msg);
}
//finally
//{
// myConn.Close();
//}
}
Any suggestions to what could have gone wrong?
You have forgotten to add the parameters to your command and you close the connection before the call of the method. I propose you using:
private void Save(string hfname, string hlname, string hemail, string hcomment)
{
SqlConnection myConn = new SqlConnection(GetConnectionString());
String sql = "INSERT INTO helpdesk (First_Name, Last_Name, Email, Comments) VALUES " + " (#f_name, #l_name, #email, #comment)";
SqlCommand cmd = new SqlCommand(sql, myConn);
ITDBDataset itdbDataSet = new ITDBDataset();
SqlDataAdapter dataAdapter;
try
{
myConn.Open();
dataAdapter = new SqlDataAdapter(cmd);
dataAdapter.Fill(itdbDataSet);
SqlParameter[] param = new SqlParameter[6];
//para,[0]
param[0] = new SqlParameter("#f_name", System.Data.SqlDbType.VarChar, 50);
param[1] = new SqlParameter("#l_name", System.Data.SqlDbType.VarChar, 50);
param[2] = new SqlParameter("#email", System.Data.SqlDbType.VarChar, 30);
param[3] = new SqlParameter("#comment", System.Data.SqlDbType.VarChar, 600);
param[0].Value = hfname;
param[1].Value = hlname;
param[2].Value = hemail;
param[3].Value = hcomment;
cmd.Parameters.AddRange(param);//add the parameters
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
//SqlDataReader reader = cmd.ExecuteReader();
myConn.Close();
}
I suggest you use AddWithValue eg
SqlConnection myConn = new SqlConnection(GetConnectionString());
String sql =
"INSERT INTO helpdesk (First_Name, Last_Name, Email, Comments) VALUES " +
" (#f_name, #l_name, #email, #comment)";
SqlCommand cmd = new SqlCommand(sql, myConn);
cmd.Parameters.AddWithValue("#f_name",hfname);
cmd.Parameters.AddWithValue("#l_name",hlname);
cmd.Parameters.AddWithValue("#email",hemail);
cmd.Parameters.AddWithValue("#comment",hcomment);
ITDBDataset itdbDataSet = new ITDBDataset();
SqlDataAdapter dataAdapter;
try
{
myConn.Open();
dataAdapter = new SqlDataAdapter(cmd);
dataAdapter.Fill(itdbDataSet);
myConn.Close();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Not Added, check context!";
msg += ex.Message;
throw new Exception(msg);
}
Related
Good day all! I'm having a minor issue with the insert to my program. See, the code has no errors but I'm having an OleDb exception when trying to insert. The other parts of my project work fine but there is a tiny issue here that I can't seem to find
public void Insert()
{
//myDb = new OleDbConnection(conn + dbFile);
myDb.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM Employee", myDb);
//
OleDbCommand cmd = new OleDbCommand("INSERT INTO Employee(Username, Password, email, phone) VALUES ('" + insUn + "','" + insPass + "','" + insNm + "','" + insNmr + "')", myDb);
adapter.InsertCommand = cmd;
adapter.InsertCommand.ExecuteNonQuery();
DataSet ds = new DataSet();
adapter.Fill(ds, "Employee");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Employee";
myDb.Close();
}
The other functions such as the search and delete work but I can't find the problem here
These are the exceptions:
try
{
if (textBox2.Text != "")
{
insUn = textBox2.Text;
insNmr = textBox4.Text;
insPass = textBox3.Text;
insNm = textBox5.Text;
}
Insert();
}
catch (OleDbException ex)
{
MessageBox.Show("Error, please try again", "Exception", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
}
catch (FormatException ex)
{
MessageBox.Show("One or more fields have not been entered. Please check and re-enter", "Missing fields", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
enter code here
Abdellah's answer will work, but be aware for SQL Injection attacks when building your query string. You should build it like this:
OleDbCommand cmd = new OleDbCommand("INSERT INTO Employee(Username, Password, email, phone) VALUES (#p1, #p2, #p3, #p4)", myDb);
int maxSize = 50;
cmd.Paramters.Add("#p1", SqlDbType.VarChar, maxSize).Value = insUn;
cmd.Parameters.Add("#p2", SqlDbType.VarChar, maxSize).Value = insPass;
cmd.Parameters.Add("#p3", SqlDbType.VarChar, maxSize).Value = insNm;
cmd.Parameters.Add("#p4", SqlDbType.VarChar, maxSize).Value = insNmr;
I advice you to use the Parameter to avoid SQL injections , and put the brackets [] in query for [Password] because it's a keyword like below :
public void Insert()
{
//myDb = new OleDbConnection(conn + dbFile);
myDb.Open();
OleDbCommand cmd = new OleDbCommand("INSERT INTO Employee(Username, [Password], email, phone) VALUES (#Username, #Password, #email, #phone)", myDb);
cmd.Parameters.AddWithValue("#Username", insUn);
cmd.Parameters.AddWithValue("#Password", insPass);
cmd.Parameters.AddWithValue("#email", insNm);
cmd.Parameters.AddWithValue("#phone", insNmr);
cmd.ExecuteNonQuery();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM Employee", myDb);
DataSet ds = new DataSet();
adapter.Fill(ds, "Employee");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Employee";
myDb.Close();
}
I have created one method in data Access class to select data from database with parameter. I just want to use parameterized query.
Method Is :
public DataTable executeSelectQuery(String _query, SqlParameter[] sqlParameter)
{
SqlCommand myCommand = new SqlCommand();
DataTable dataTable = new DataTable();
dataTable = null;
DataSet ds = new DataSet();
try
{
myCommand.Connection = openConnection();
myCommand.CommandText = _query;
myCommand.Parameters.AddRange(sqlParameter);
myCommand.ExecuteNonQuery();
myAdapter.SelectCommand = myCommand;
myAdapter.Fill(ds);
dataTable = ds.Tables[0];
}
catch (SqlException e)
{
return null;
}
finally
{
myCommand.Connection = CloseConnection();
}
return dataTable;
}
but I can't understand how to use this method to fetch data and how to pass parameter?
My query may be "select password from tblUsers where email=#email" How to pass #email at business layer?
How to make method in data access class for getting Scalar value?
public string getpasswrd(string unm)
{
con.Open();
string cpaswrd;
cmd1 = new SqlCommand("select password from tbl_login where username='" + unm + "'", con);
cpaswrd = (String)cmd1.ExecuteScalar();
con.Close();
return cpaswrd;
}
SqlParameter param;
cmd1 = new SqlCommand("select password from tbl_login where username=#username, con);
param = new SqlParameter("#username", SqlDbType.VarChar);
param.Direction = ParameterDirection.Input;
param.Value = unm;
cmd1.Parameters.Add(param);
cpaswrd = cmd1.ExecuteScalar().ToString();
You just need to use the same name in the sql parameter:
new SqlParameter("email", "myemail#gmail.com")
So i am using a stored procedure to select a registry from a DB, the only thing the stored procedure does is SELECT ... The thing is that i use that stored procedure to fill a DataSet wich i return in my WebService. The problem comes when i want to send an exception instead of the DataSet, since the stored procedure checks on the DB and returns an empty row the DataSet fills with nothing and does not send me to an Exception ... Now, i save all my exceptions in a log table in the same DB ... My question is, can i go to the Exception block if the SELECT values are empty??
Here is my Code
[WebMethod(Description = "Private", EnableSession = false)]
public DataSet M812(string p_transaction)
{
string extran, enclosure, eDate;
try
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CTSSQL"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "dbo.sp_M812";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#p_trans", SqlDbType.NChar, 18).Value = p_transaction;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "Entradas");
con.Open();
cmd.ExecuteNonQuery();
con.Close();
cmd.Connection.Close();
return ds;
}
catch(SqlException Ex)
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CTSSQL"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "dbo.sp_reqdataerrorlog";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#p_inTrans", SqlDbType.NChar, 12).Value = p_transaction;
cmd.Parameters.Add("#vo_enclosure", SqlDbType.VarChar, 250).Direction = ParameterDirection.Output;
cmd.Parameters.Add("#vo_trans", SqlDbType.VarChar, 10).Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
cmd.Connection.Close();
enclosure = "" + cmd.Parameters["#vo_enclosure"].Value;
extran = "" + cmd.Parameters["#vo_trans"].Value;
SqlConnection con2 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CTSSQL"].ConnectionString);
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = con2;
cmd2.CommandText = "dbo.sp_errorlog";
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.Parameters.Add("#p_inTrans", SqlDbType.NChar, 12).Value = p_transaction;
cmd2.Parameters.Add("#p_enclosure", SqlDbType.NChar, 6).Value = enclosure;
cmd2.Parameters.Add("#p_trans", SqlDbType.NChar, 18).Value = extran;
cmd2.Parameters.Add("#p_method", SqlDbType.NChar, 6).Value = "812";
cmd2.Parameters.Add("#p_message", SqlDbType.NVarChar, 250).Value = "SQL Error: " + Ex.Message;
cmd2.Parameters.Add("#vo_message", SqlDbType.VarChar, 250).Direction = ParameterDirection.Output;
cmd2.Parameters.Add("#vo_errorDate", SqlDbType.DateTime).Direction = ParameterDirection.Output;
con2.Open();
cmd2.ExecuteNonQuery();
con2.Close();
cmd2.Connection.Close();
eDate = "" + cmd2.Parameters["#vo_errorDate"].Value;
SqlConnection con3 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CTSSQL"].ConnectionString);
SqlCommand cmd3 = new SqlCommand();
cmd3.Connection = con3;
cmd3.CommandText = "dbo.sp_selecterrorlog";
cmd3.CommandType = CommandType.StoredProcedure;
cmd3.Parameters.Add("#p_trans", SqlDbType.NChar, 18).Value = p_transaction;
cmd3.Parameters.Add("#p_date", SqlDbType.DateTime).Value = eDate;
SqlDataAdapter da = new SqlDataAdapter(cmd3);
DataSet ds = new DataSet();
da.Fill(ds, "ErrorLog");
con3.Open();
cmd3.ExecuteNonQuery();
con3.Close();
cmd3.Connection.Close();
return ds;
}
catch (Exception Ex)
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CTSSQL"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "dbo.sp_reqdataerrorlog";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#p_inTrans", SqlDbType.NChar, 12).Value = p_transaction;
cmd.Parameters.Add("#vo_enclosure", SqlDbType.VarChar, 250).Direction = ParameterDirection.Output;
cmd.Parameters.Add("#vo_trans", SqlDbType.VarChar, 10).Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
cmd.Connection.Close();
enclosure = "" + cmd.Parameters["#vo_enclosure"].Value;
extran = "" + cmd.Parameters["#vo_trans"].Value;
SqlConnection con2 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CTSSQL"].ConnectionString);
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = con2;
cmd2.CommandText = "dbo.sp_errorlog";
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.Parameters.Add("#p_inTrans", SqlDbType.NChar, 12).Value = p_transaction;
cmd2.Parameters.Add("#p_enclosure", SqlDbType.NChar, 6).Value = enclosure;
cmd2.Parameters.Add("#p_trans", SqlDbType.NChar, 18).Value = extran;
cmd2.Parameters.Add("#p_method", SqlDbType.NChar, 6).Value = "812";
cmd2.Parameters.Add("#p_message", SqlDbType.NVarChar, 250).Value = "WEB Error: " + Ex.Message;
cmd2.Parameters.Add("#vo_message", SqlDbType.VarChar, 250).Direction = ParameterDirection.Output;
cmd2.Parameters.Add("#vo_errorDate", SqlDbType.DateTime).Direction = ParameterDirection.Output;
con2.Open();
cmd2.ExecuteNonQuery();
con2.Close();
cmd2.Connection.Close();
eDate = "" + cmd2.Parameters["#vo_errorDate"].Value;
SqlConnection con3 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CTSSQL"].ConnectionString);
SqlCommand cmd3 = new SqlCommand();
cmd3.Connection = con3;
cmd3.CommandText = "dbo.sp_selecterrorlog";
cmd3.CommandType = CommandType.StoredProcedure;
cmd3.Parameters.Add("#p_trans", SqlDbType.NChar, 18).Value = p_transaction;
cmd3.Parameters.Add("#p_date", SqlDbType.DateTime).Value = eDate;
SqlDataAdapter da = new SqlDataAdapter(cmd3);
DataSet ds = new DataSet();
da.Fill(ds, "ErrorLog");
con3.Open();
cmd3.ExecuteNonQuery();
con3.Close();
cmd3.Connection.Close();
return ds;
}
}
Here is how you can check if the DataSet has any rows in any table:
bool hasRows = ds.Tables.Cast<DataTable>().Any(table => table.Rows.Count != 0);
Now you have a choice as to how to get the error data returned to the caller:
Pull out the error building logic into a separate method that your exception catch handler block and your if condition can both call, like this:
private void BuildAndReturnErrorDataSet()
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CTSSQL"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "dbo.sp_reqdataerrorlog";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#p_inTrans", SqlDbType.NChar, 12).Value = p_transaction;
cmd.Parameters.Add("#vo_enclosure", SqlDbType.VarChar, 250).Direction = ParameterDirection.Output;
cmd.Parameters.Add("#vo_trans", SqlDbType.VarChar, 10).Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
cmd.Connection.Close();
enclosure = "" + cmd.Parameters["#vo_enclosure"].Value;
extran = "" + cmd.Parameters["#vo_trans"].Value;
SqlConnection con2 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CTSSQL"].ConnectionString);
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = con2;
cmd2.CommandText = "dbo.sp_errorlog";
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.Parameters.Add("#p_inTrans", SqlDbType.NChar, 12).Value = p_transaction;
cmd2.Parameters.Add("#p_enclosure", SqlDbType.NChar, 6).Value = enclosure;
cmd2.Parameters.Add("#p_trans", SqlDbType.NChar, 18).Value = extran;
cmd2.Parameters.Add("#p_method", SqlDbType.NChar, 6).Value = "812";
cmd2.Parameters.Add("#p_message", SqlDbType.NVarChar, 250).Value = "WEB Error: " + Ex.Message;
cmd2.Parameters.Add("#vo_message", SqlDbType.VarChar, 250).Direction = ParameterDirection.Output;
cmd2.Parameters.Add("#vo_errorDate", SqlDbType.DateTime).Direction = ParameterDirection.Output;
con2.Open();
cmd2.ExecuteNonQuery();
con2.Close();
cmd2.Connection.Close();
eDate = "" + cmd2.Parameters["#vo_errorDate"].Value;
SqlConnection con3 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CTSSQL"].ConnectionString);
SqlCommand cmd3 = new SqlCommand();
cmd3.Connection = con3;
cmd3.CommandText = "dbo.sp_selecterrorlog";
cmd3.CommandType = CommandType.StoredProcedure;
cmd3.Parameters.Add("#p_trans", SqlDbType.NChar, 18).Value = p_transaction;
cmd3.Parameters.Add("#p_date", SqlDbType.DateTime).Value = eDate;
SqlDataAdapter da = new SqlDataAdapter(cmd3);
DataSet ds = new DataSet();
da.Fill(ds, "ErrorLog");
con3.Open();
cmd3.ExecuteNonQuery();
con3.Close();
cmd3.Connection.Close();
return ds;
}
if(!hasRows)
{
// Call error data set building logic
BuildAndReturnErrorDataSet();
}
catch (Exception Ex)
{
// Call error data set building logic
BuildAndReturnErrorDataSet();
}
Raise exception if hasRows is false - not recommended as this is using exception handling to cause program control flow, but it technically will work.
I recieve the following error when I try to execute this code. But I added it to my commands. Can someone point out the step that overlooked? Thanks.
Procedure or function 'usps_getContactDetails' expects parameter '#aspContactID', which was not supplied.
SqlConnection conn = new SqlConnection(GetConnString());
SqlCommand cmd = new SqlCommand("usps_getContactDetails", conn);
SqlParameter parmContactID = new SqlParameter("#aspContactID", Convert.DBNull);
cmd.Parameters.Add(parmContactID);
parmContactID.Direction = ParameterDirection.Input;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
conn.Open();
DataSet cusDS = new DataSet();
da.Fill(cusDS, "Contacts");
When doing a SqlCommand and calling a stored procedure, you need to implicity set your SqlCommand to be a StoredProcedure.
using(SqlConnection con = new SqlConnection(""))
{
//Set up your command
SqlCommand cmd = new SqlCommand("[Procedure]", con);
cmd.CommandType = CommandType.StoredProcedure;
//Add your parameters
cmd.Parameters.AddWithValue("#aspContactID", "");
//Declare your data adapter
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds, "Contacts");
}
Follow the above format and you should be fine. Your procedure isn't working for one of two reasons, you were missing the line of code which makes your code work in this case is cmd.CommandType = CommandType.StoredProcedure; or because your parameter is DBNull the procedure says it doesn't have any recognition of that parameter. If you have a parameter which can be null or empty in a stored procedure then do the following:
Create Procedure [dbo].[Example]
#Test as Varchar(100) = ''
As
protected void Page_Load(object sender, EventArgs e)
{
}
private void OpenCon()
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["DbPrepConnectionString"].ConnectionString.ToString());
try
{
con.Open();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
private void SubmitData()
{
OpenCon();
string sp = "sp_InsertRecord";
cmd = new SqlCommand(sp, con);
cmd.CommandType = CommandType.StoredProcedure;
//add parameters...
cmd.Parameters.Add(new SqlParameter("#Name", SqlDbType.VarChar, 50));
cmd.Parameters.Add(new SqlParameter("#UserId", SqlDbType.Int));
cmd.Parameters.Add (new SqlParameter ("#ProductName",SqlDbType .VarChar,50));
cmd.Parameters.Add(new SqlParameter("#Price", SqlDbType.Money));
//set paarameters....
cmd.Parameters["#Name"].Value = txtName.Text.ToString();
cmd.Parameters["#UserId"].Value = txtUserId.Text.ToString();
cmd.Parameters["#ProductName"].Value = txtProductName.Text.ToString();
cmd.Parameters["#Price"].Value = txtPrice.Text.ToString();
cmd.ExecuteNonQuery();
lblMessage.Text = "data inserted successfully";
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
SubmitData();
}
private void FindData()
{
OpenCon();
string s = "sp_FindRecord";
cmd = new SqlCommand(s, con);
cmd.Parameters.Add(new SqlParameter("#Id", SqlDbType.Int));
cmd.Parameters["#Id"].Value = txtName.Text.ToString();
cmd.CommandType = CommandType.StoredProcedure;
ad = new SqlDataAdapter(cmd);
ds = new DataSet();
ad.Fill(ds);
dt = ds.Tables[0];
currow = 0;
FillControls();
}
private void FillControls()
{
txtOrderId.Text = dt.Rows[currow].ItemArray[0].ToString();
txtUserId.Text = dt.Rows[currow].ItemArray[1].ToString();
txtProductName.Text = dt.Rows[currow].ItemArray[2].ToString();
txtPrice.Text = dt.Rows[currow].ItemArray[3].ToString();
}
protected void btnFind_Click(object sender, EventArgs e)
{
FindData();
}
}
}'
I am using the following code to bind BusinessID as the DataValueField of the ddlIndustry dropdown. What I want to do is save the selected ID to a different table (Company). I am doing this with ddlIndustry.SelectedValue. For some reason, the first value is always saved (1), and not the selected value. Do you have any ideas as to why this might be happening?
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindCountry();
BindIndustry();
}
private void BindCountry()
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("countries.xml"));
foreach (XmlNode node in doc.SelectNodes("//country"))
{
ddlCountry.Items.Add(new ListItem(node.InnerText, node.Attributes["code"].InnerText));
ddlCountry.SelectedIndex = 94;
}
}
private void BindIndustry()
{
SqlCommand cmd = null;
SqlConnection conn = new SqlConnection(GetConnectionString());
conn.Open();
cmd = new SqlCommand("Select Industry, BusinessID FROM BusinessType", conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
ddlIndustry.DataSource = ds;
ddlIndustry.DataTextField = "Industry";
ddlIndustry.DataValueField = "BusinessID";
ddlIndustry.DataBind();
//ddlIndustry.Items.Insert(0, new System.Web.UI.WebControls.ListItem("-- Please Select Industry --", "0"));
}
private void ExecuteCompanyDetailsInsert()
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO Company (BusinessID, CompanyName, Email, AddressLine1, AddressLine2, Location, Telephone) VALUES "
+ " (#BusinessID, #CompanyName, #Email, #AddressLine1, #AddressLine2, #Location, #Telephone)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[7];
param[0] = new SqlParameter("#BusinessID", SqlDbType.Int);
param[1] = new SqlParameter("#CompanyName", SqlDbType.VarChar, 50);
param[2] = new SqlParameter("#Email", SqlDbType.VarChar, 50);
param[3] = new SqlParameter("#AddressLine1", SqlDbType.VarChar, 50);
param[4] = new SqlParameter("#AddressLine2", SqlDbType.VarChar, 50);
param[5] = new SqlParameter("#Location", SqlDbType.VarChar, 50);
param[6] = new SqlParameter("#Telephone", SqlDbType.VarChar, 50);
param[0].Value = ddlIndustry.SelectedValue;
param[1].Value = company_name.Text;
param[2].Value = company_email.Text;
param[3].Value = address_line_1.Text;
param[4].Value = address_line_2.Text;
param[5].Value = ddlCountry.SelectedItem.Text;
param[6].Value = telephone.Text;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
First of all modify this code, because when your page is postback to server, your industry dropdown bind again and your selected value lost
if (!Page.IsPostBack)
{
BindCountry();
BindIndustry();
}
and then you can get selected value
ddlIndustry.SelectedValue