How to achieve the requirements below:
The Retrieve button click event:
if user doesn't enter CustID in txtCustID need to inform them to enter Customer Id via lblMessage;
if entered CustId doesn't exist in database inform user that it doesn't exist via lblMessage.
The Update button click event - need to ensure that Customer ID already exists in the database.
The Delete button click event: same requirements as for Retrieve button.
I must use error/exception handling (try-catch) to achieve these (project requirement). I spent hours trying, but no success. I would be very grateful for some help! My code is below:
namespace ACME
{
public partial class Customer : System.Web.UI.Page
{
SqlConnection conn;
SqlDataAdapter adapter = new SqlDataAdapter();
DataTable table = new DataTable();
SqlCommand command = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
}
private void Page_PreInit(object sender, EventArgs e)
{
HttpCookie setTheme = Request.Cookies.Get("UserSelectedTheme");
if (setTheme != null)
{
Page.Theme = setTheme.Value;
}
}
protected void Clear()
{
txtCustID.Text = "";
txtFirstname.Text = "";
txtSurname.Text = "";
rbtGender.SelectedValue = "";
txtAge.Text = "";
txtAddress1.Text = "";
txtAddress2.Text = "";
txtCity.Text = "";
txtPhone.Text = "";
txtMobile.Text = "";
txtEmail.Text = "";
txtEmail2.Text = "";
}
protected void btnNew_Click(object sender, EventArgs e)
{
SqlDataAdapter adapter1 = new SqlDataAdapter();
DataTable table1 = new DataTable();
SqlCommand command1 = new SqlCommand();
Clear();
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
command1.Connection = conn;
command1.CommandType = CommandType.StoredProcedure;
command1.CommandText = "LargestCustID";
command1.Connection.Open();
int id = (int)command1.ExecuteScalar() + 1;
txtCustID.Text = id.ToString();
command1.Dispose();
conn.Close();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "AddCustomer";
command.Connection.Open();
command.Parameters.AddWithValue("#CustID",
int.Parse(txtCustID.Text));
command.Parameters.AddWithValue("#Firstname", txtFirstname.Text);
command.Parameters.AddWithValue("#Surname", txtSurname.Text);
command.Parameters.AddWithValue("#Gender", rbtGender.SelectedValue);
command.Parameters.AddWithValue("#Age", int.Parse(txtAge.Text));
command.Parameters.AddWithValue("#Address1", txtAddress1.Text);
command.Parameters.AddWithValue("#Address2", txtAddress2.Text);
command.Parameters.AddWithValue("#City", txtCity.Text);
command.Parameters.AddWithValue("#Phone", txtPhone.Text);
command.Parameters.AddWithValue("#Mobile", txtMobile.Text);
command.Parameters.AddWithValue("#Email", txtEmail.Text);
adapter.InsertCommand = command;
adapter.InsertCommand.ExecuteNonQuery();
lblMessage.Text = "The new record has been added to the database!";
command.Connection.Close();
Clear();
}
protected void btnRetrieve_Click(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "GetCustID";
command.Connection.Open();
SqlParameter param = new SqlParameter();
param.ParameterName = "#CustID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = int.Parse(txtCustID.Text);
command.Parameters.Add(param);
adapter.SelectCommand = command;
adapter.Fill(table);
int id = table.Rows.Count;
if (id == 0)
{
lblMessage.Text = "Customer ID does not exists!";
}
else
{
lblMessage.Text = "";
txtFirstname.Text = table.Rows[0].Field<string>("Firstname");
txtFirstname.DataBind();
txtSurname.Text = table.Rows[0].Field<string>("Surname");
txtSurname.DataBind();
txtAge.Text = table.Rows[0].Field<int>("Age").ToString();
txtAge.DataBind();
txtAddress1.Text = table.Rows[0].Field<string>("Address1");
txtAddress1.DataBind();
txtAddress2.Text = table.Rows[0].Field<string>("Address2");
txtAddress2.DataBind();
txtCity.Text = table.Rows[0].Field<string>("City");
txtCity.DataBind();
txtPhone.Text = table.Rows[0].Field<string>("Phone");
txtPhone.DataBind();
txtMobile.Text = table.Rows[0].Field<string>("Mobile");
txtMobile.DataBind();
txtEmail.Text = table.Rows[0].Field<string>("Email");
txtEmail.DataBind();
}
command.Connection.Close();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "UpdateCustomer";
command.Connection.Open();
command.Parameters.AddWithValue("#CustID",
int.Parse(txtCustID.Text));
command.Parameters.AddWithValue("#Firstname", txtFirstname.Text);
command.Parameters.AddWithValue("#Surname", txtSurname.Text);
command.Parameters.AddWithValue("#Gender", rbtGender.SelectedValue);
command.Parameters.AddWithValue("#Age", int.Parse(txtAge.Text));
command.Parameters.AddWithValue("#Address1", txtAddress1.Text);
command.Parameters.AddWithValue("#Address2", txtAddress2.Text);
command.Parameters.AddWithValue("#City", txtCity.Text);
command.Parameters.AddWithValue("#Phone", txtPhone.Text);
command.Parameters.AddWithValue("#Mobile", txtMobile.Text);
command.Parameters.AddWithValue("#Email", txtEmail.Text);
lblMessage.Text = "The record has been updated!";
command.Connection.Close();
Clear();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "DeleteCustomer";
command.Connection.Open();
SqlParameter param = new SqlParameter();
param.ParameterName = "#CustID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = int.Parse(txtCustID.Text);
command.Parameters.Add(param);
adapter.DeleteCommand = command;
adapter.DeleteCommand.ExecuteNonQuery();
int id = (int)param.Value;
command.Connection.Close();
}
catch (Exception ex)
{
lblMessage.Text += "Please enter Customer ID!";
}
try
{
lblMessage.Text = "";
SqlParameter param = new SqlParameter();
param.ParameterName = "#CustID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = int.Parse(txtCustID.Text);
command.Parameters.Add(param);
adapter.DeleteCommand = command;
adapter.DeleteCommand.ExecuteNonQuery();
int id = table.Rows.Count;
id = (int)param.Value;
lblMessage.Text += "Customer record has been deleted";
command.Connection.Close();
}
catch (Exception ex)
{
lblMessage.Text = "Customer ID doesnot exists!";
}
Clear();
}
public string CustID { get; set; }
}
}
It sounds like you are trying to control flow of your application by use of exceptions. There are many reasons against this approach:
1) Code is difficult to understand and to debug.
2) Throwing exceptions in .Net is expensive.
3) If exception control flow of application how do you differentiate them from a real exceptions (thrown when something doesn't work as expected)?
If, on the other hand, you want to throw an exception when any of the scenarios you listed in the question happens then you can use standard .Net Exception class:
if (string.IsNullOrWhiteSpace(txtCustID.Text))
{
throw new Exception("Id not provided.");
}
Or you can create a custom exception to provide some more specific information:
public class IdNotProvidedException : Exception
{
public string MyCommandName { get; set; }
public IdNotProvidedException(string msg)
: base(msg)
{
}
public IdNotProvidedException(string msg, string myCommandName)
: base(msg)
{
this.MyCommandName = myCommandName;
}
}
And then you initialize and throw your custom exception.
Lastly, there are already places in your code, though not mentioned in your question, that are worth wrapping in a try...catch block. Basically, any place where you connect with the server may result in something unexpected (for instance, the server may not be available).
Related
I have a problem with data management in the postgre database. I`m connected, now i want to add any value, but that what i wrote dosent work.
protected void Page_Load(object sender, EventArgs e)
{
try
{
Label1.Text = "Połączenie z bazą danych zakonczońe sukcesem";
NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;Port=5432;Database=dt_PackageWarehouse;User Id=postgres;Password=321qweQAZ");
conn.Open();
NpgsqlCommand comm = new NpgsqlCommand();
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = "select * from magazynpaczek";
NpgsqlDataAdapter nda = new NpgsqlDataAdapter(comm);
DataTable dt = new DataTable();
nda.Fill(dt);
comm.Dispose();
conn.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception)
{
Label1.Text = "Połączenie z bazą danych zakonczońe niepowodzeniem";
}
}
protected void btnDodaj_Click(object sender, EventArgs e)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;Port=5432;Database=dt_PackageWarehouse;User Id=postgres;Password=321qweQAZ");
string query = "Insert into public.magazynpaczek(id, nazwafirmynadawcy, imienadawcy, nazwiskonadawcy, nrtelefonunadawcy, miastonadawcy, ulicanadawcy, nazwafirmyodbiorcy," +
" imieodbiorcy, nazwiskoodbiorcy, nrtelefonuodbiorcy, miastoodbiorcy, ulicaodbiorcy, nrprzesylki, datadoreczenia) VALUES(#NFN, #txtIN, #txtNN, #txtNTN, #txtMN," +
"#txtUN, #txtNFO, #txtIO, #txtNO, #txtNTO, #txtMO, #txtUO, #txtNP, #txtDD)";
NpgsqlCommand comm = new NpgsqlCommand(query, conn);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
you have to create and add a parameter for each insert value:
var query = "Insert into public.magazynpaczek(id, nazwafirmynadawcy, imienadawcy, nazwiskonadawcy, nrtelefonunadawcy, miastonadawcy, ulicanadawcy, nazwafirmyodbiorcy," +
" imieodbiorcy, nazwiskoodbiorcy, nrtelefonuodbiorcy, miastoodbiorcy, ulicaodbiorcy, nrprzesylki, datadoreczenia) VALUES(#NFN, #txtIN, #txtNN, #txtNTN, #txtMN," +
"#txtUN, #txtNFO, #txtIO, #txtNO, #txtNTO, #txtMO, #txtUO, #txtNP, #txtDD)";
IDbCommand command = conn.CreateCommand();
command.CommandText = query;
var parameter = command.CreateParameter();
parameter.ParameterName = "NFN";
parameter.Value = nfn;
command.Parameters.Add(parameter);
parameter = command.CreateParameter();
parameter.ParameterName = "txtIN";
parameter.Value = txtIN.text;
command.Parameters.Add(parameter);
.... and so on
conn.Open();
command.ExecuteNonQuery();
conn.Close();
private void button1_Click(object sender, EventArgs e)
{
int f = 1;
SqlConnection con = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; database = 'C:\Users\Emil Sharier\Documents\testDB.mdf'; Integrated Security = True; Connect Timeout = 30");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
int bal = 0;
string cmdstr = "select * from users where userid='"+ Form1.userid+"';";
cmd.CommandText = cmdstr;
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
bal = int.Parse(dr[2].ToString());
int draw = int.Parse(textBox1.Text);
if(draw > bal)
{
MessageBox.Show("Insufficient balance!");
return;
}
else
{
bal -= draw;
cmdstr = "update users set balance='"+bal.ToString()+"' where userid='"+ Form1.userid + "';";
SqlDataAdapter da = new SqlDataAdapter();
da.UpdateCommand = con.CreateCommand();
da.UpdateCommand.CommandText = cmdstr;
try
{
da.UpdateCommand.ExecuteNonQuery();
}
catch(Exception ex)
{
f = 0;
}
if (f == 1)
MessageBox.Show("Money withdrawn succesfully!");
else
MessageBox.Show("Enter correct amount!");
}
con.Close();
}
I am getting an "InvalidOperationException" while executing this program. I am not sure what the error is. Please help.
da.UpdateCommand.ExecuteNonQuery() is not getting executed
......
var sqlcmd = new SqlCommand(cmdstr, con);
.....
try
{
sqlcmd.ExecuteNonQuery();
....
Don't use adapter.
And yes. Faster of all try to close connection and open new one for update operation.
I created a folder on a webform in visual studio for images and titled as (Invoices), I want to save the root of images in MySql database and display the images on a panel one the webpage. The image has been saved on the folder but not on database.
The Codes I have tried
protected void Page_Load(object sender, EventArgs e)
{
string connection = "server=localhost; userid= ; password= ; database=admindb; allowuservariables=True";
MySqlConnection cn = new MySqlConnection(connection);
try
{
string sqlcmd = "SELECT PicAddress FROM InvoicesFP WHERE InvoicesFP_ID=#InvoicesFP_ID";
cn.Open();
MySqlCommand cmd = new MySqlCommand(sqlcmd, cn);
cmd.CommandType = CommandType.Text;
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string url = rdr["PicAddress"].ToString();
Image1.ImageUrl = url;
}
}
catch (Exception ex)
{
throw ex;
}
cn.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
#region fileupload
var FileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName).Substring(1);
string SaveLocation = Server.MapPath("Invoices\\") + Guid.NewGuid().ToString("N") + FileExtension;
MySqlConnection connection = new MySqlConnection("server=localhost; userid=root; password=admin1234; database=admindb; allowuservariables=True");
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "insert into invoicesfp (PicAddress), VALUES (#PicAddress)";
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("PicAddress", Server.MapPath("~/Invoices"));
cmd.Connection.Open();
cmd.BeginExecuteNonQuery();
cmd.Connection.Close();
try
{
FileUpload1.PostedFile.SaveAs(SaveLocation);
}
catch (Exception ex)
{
if (ex is ArgumentNullException || ex is NullReferenceException)
{
throw ex;
}
}
string PicAddress = "~/Invoices/" + SaveLocation;
}
#endregion
}
Update
Try this Code first, using this sample you do not need to use Rename Method And whatever its Extension is, it is supported:
#region fileupload
var FileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName).Substring(1);
string SaveLocation = Server.MapPath("Invoices\\") + Guid.NewGuid().ToString("N") + "." + FileExtension;
try
{
FileUpload1.PostedFile.SaveAs(SaveLocation);
}
catch (Exception ex)
{
if (ex is ArgumentNullException || ex is NullReferenceException)
{
throw ex;
}
}
string PicAddress = "~/Invoices/" + SaveLocation;
#endregion
MySqlConnection connection = new MySqlConnection("server=localhost; userid=root; password=admin1234; database=admindb; allowuservariables=True");
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "INSERT INTO InvoicesFP (PicAddress) VALUES (#PicAddress)";
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("PicAddress", "PicAddress");
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
then in your page_load you can call the Select Query to get the Address out database and pass it over to control e.g:
const string DB_CONN_STR = "Server=etc;Uid=etc;Pwd=etc;Database=etc;";
MySqlConnection cn = new MySqlConnection(DB_CONN_STR);
try {
string sqlCmd = "SELECT PicAddress FROM [YourTable] where Id == PicAddress id";
cn.Open(); // have to explicitly open connection (fetches from pool)
MySqlCommand cmd = new MySqlCommand(sqlCmd, cn);
cmd.CommandType = CommandType.Text;
MySqlDataReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
string url = rdr["Name of the Field Assuming PicAddress"].ToString();
Image1.ImageUrl = url;
}
}
catch(Exception ex)
{
throw ex;
}
Thats All - Happy Coding
this is my code,when the textbox content changes the datas required have to retrieved from the databse and displayed in the labels specified.
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Match match = Regex.Match(TextBox1.Text, #"^\d{4}[A-Z]{5}\d{3}$");
if (match.Success)
{
try
{
DropDownList1.Focus();
string dpt = (string)Session["deptmnt"];
idd = TextBox1.Text;
Label33.Text = idd;
string val = idd;
string con = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
SqlConnection con1 = new SqlConnection(con);
con1.Open();
// string val1 = dpt;
try
{
String str = "SELECT * from student where sid=#val";
SqlCommand cmd = new SqlCommand(str, con1);
cmd.CommandType = CommandType.Text;
SqlParameter sql;
cmd.Parameters.Clear();
sql = cmd.Parameters.Add("#val", SqlDbType.VarChar, 20);
sql.Value = val;
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows == false)
{
Label35.Visible = true;
TextBox1.Text = "";
}
else
{
{
Panel3.Visible = true;
DropDownList1.Focus();
while (reader.Read()) // if can read row from database
{
Panel3.Visible = true;
Label3.Text = reader["sname"].ToString();
Label5.Text = reader["dept"].ToString();
Label25.Text = reader["yr"].ToString();
}
cmd.Parameters.Clear();
{
string val1 = idd;
string str2 = "SELECT bid from studentissuebook where sid=#val1 AND status='" + "lost" + "'";
SqlCommand cmd2 = new SqlCommand(str2, con1);
cmd2.CommandType = CommandType.Text;
cmd2.Parameters.Clear();
SqlParameter sql2;
sql2 = cmd2.Parameters.Add("#val1", SqlDbType.VarChar, 20);
sql2.Value = val1;
SqlDataReader reader1 = cmd2.ExecuteReader();
if (reader1.HasRows == false)
{
TextBox1.Text = "";
Label39.Visible = true;
Panel3.Visible = false;
}
else
{
DropDownList1.Focus();
while (reader1.Read()) // if can read row from database
{
DropDownList1.Items.Add(reader1[0].ToString());
}
DropDownList1.Focus();
}
}
}
}
con1.Close();
}
catch(Exception ex)
{
TextBox1.Text=ex.ToString();
}
}
catch (Exception ex)
{
TextBox1.Text = ex.ToString();
}
} else
{
formatlabel.Visible = true;
}
}
but,when i run the code,i get an error "The variable name '#sid' has already been declared. Variable names must be unique within a query batch or stored procedure.",I googled, generally this error occurs when there is a for loop or any loops,but i do not have any loops in my code.so im unable to find the cause
Try using two separate connection and command objects, like this:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Match match = Regex.Match(TextBox1.Text, #"^\d{4}[A-Z]{5}\d{3}$");
if (match.Success)
{
DropDownList1.Focus();
string dpt = (string) Session["deptmnt"];
idd = TextBox1.Text;
Label33.Text = idd;
string val = idd;
string con = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
using (SqlConnection con1 = new SqlConnection(con))
{
String str = "SELECT * from student where sid=#val";
con1.Open();
using (SqlCommand cmd = new SqlCommand(str, con1))
{
cmd.CommandType = CommandType.Text;
SqlParameter sql;
cmd.Parameters.Clear();
sql = cmd.Parameters.Add("#val", SqlDbType.VarChar, 20);
sql.Value = val;
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows == false)
{
Label35.Visible = true;
TextBox1.Text = "";
}
else
{
Panel3.Visible = true;
DropDownList1.Focus();
while (reader.Read()) // if can read row from database
{
Panel3.Visible = true;
Label3.Text = reader["sname"].ToString();
Label5.Text = reader["dept"].ToString();
Label25.Text = reader["yr"].ToString();
}
cmd.Parameters.Clear();
}
}
}
using (SqlConnection con2 = new SqlConnection(con))
{
string val1 = idd;
string str2 = "SELECT bid from studentissuebook where sid=#val1 AND status='" + "lost" + "'";
con2.Open();
using (SqlCommand cmd2 = new SqlCommand(str2, con2))
{
cmd2.CommandType = CommandType.Text;
cmd2.Parameters.Clear();
SqlParameter sql2;
sql2 = cmd2.Parameters.Add("#val1", SqlDbType.VarChar, 20);
sql2.Value = val1;
SqlDataReader reader1 = cmd2.ExecuteReader();
if (reader1.HasRows == false)
{
TextBox1.Text = "";
Label39.Visible = true;
Panel3.Visible = false;
}
else
{
DropDownList1.Focus();
while (reader1.Read()) // if can read row from database
{
DropDownList1.Items.Add(reader1[0].ToString());
}
DropDownList1.Focus();
}
}
}
}
else
{
formatlabel.Visible = true;
}
}
Note: I have removed your try-catch blocks to make the code simpler to interpret, once it is working, then please re-apply your try-catch logic where you feel appropriate. Also, I added using blocks for the SqlConnection and SqlCommand objects, this will clean up the connection even if an exception happens.
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