Trying to Insert Values into a Database from TextBoxes - c#

I am totally stumped on this one, and I'm brand new to C# so maybe one of you fine folks can help me out. I'm trying to update a database from form fields using ADO.NET.
Basically, the error I'm getting is that I am trying to insert null values into the database. The exact text of the error is:
System.ArgumentNullException: The SqlParameterCollection only accepts non-null SqlParameter type objects.
Here is the code behind for the page I am trying to use:
private void ExecuteInsert(string firstName, string lastName, string emailAddress, string city, string phone)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO contactInfo (firstName, lastName, emailAddress, city, phone) VALUES "
+ " (#firstName, #lastName, #emailAddress, #city, #phone)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[6];
param[0] = new SqlParameter("#firstName", SqlDbType.NVarChar, 25);
param[1] = new SqlParameter("#lastName", SqlDbType.NVarChar, 25);
param[2] = new SqlParameter("#emailAddress", SqlDbType.NVarChar, 30);
param[3] = new SqlParameter("#city", SqlDbType.NVarChar, 50);
param[4] = new SqlParameter("#phone", SqlDbType.Int, 10);
param[0].Value = firstName;
param[1].Value = lastName;
param[2].Value = emailAddress;
param[3].Value = city;
param[4].Value = phone;
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();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (firstName.Text != null)
{
//call the method to execute insert to the database
ExecuteInsert(firstName.Text,
lastName.Text,
emailAddress.Text,
city.Text,
phone.Text);
Response.Write("Record was successfully added!");
ClearControls(Page);
}
else
{
Response.Write("Please enter your name");
}
}
public static void ClearControls(Control Parent)
{
if (Parent is TextBox)
{ (Parent as TextBox).Text = string.Empty; }
else
{
foreach (Control c in Parent.Controls)
ClearControls(c);
}
}
If there is another way that I should be doing this, I would love to hear it. I just can't seem to find good information online.

This line:
SqlParameter[] param = new SqlParameter[6];
Should be (array is too big and you don't set last parameter):
SqlParameter[] param = new SqlParameter[5];

Change
SqlParameter[] param = new SqlParameter[6];
to
SqlParameter[] param = new SqlParameter[5];
You can add your parameters directly to cmd.Parameters without creating temp array.

Related

How to use SQL Data Adapter Update command to update a row in data table

So far I managed to use Insert command to create a new record inside a table called "Students". This is the code i used:
int ID = int.Parse( TextBox1.Text);
string name = TextBox2.Text;
string gender = TextBox3.Text;
int marks = int.Parse(TextBox4.Text);
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
//create data adapter
SqlDataAdapter adapter = new SqlDataAdapter("select * from students",con);
//create sqlcommand to store execute stored procedure
adapter.InsertCommand = new SqlCommand("spInsertStudent",con);
adapter.InsertCommand.CommandType = CommandType.StoredProcedure;
//create parameter for Return value (#ROWCOUNT)
SqlParameter parameter = adapter.InsertCommand.Parameters.Add("#ROWCOUNT",SqlDbType.Int);
parameter.Direction = ParameterDirection.ReturnValue;
adapter.InsertCommand.Parameters.Add("#ID", SqlDbType.Int, 0, "ID");
adapter.InsertCommand.Parameters.Add("#Name",SqlDbType.NVarChar,50,"Name");
adapter.InsertCommand.Parameters.Add("#Gender",SqlDbType.NVarChar,10,"Gender");
adapter.InsertCommand.Parameters.Add("#TotalMarks",SqlDbType.Int,0,"TotalMarks");
DataSet ds = new DataSet();
//DataTable students = new DataTable();
adapter.Fill(ds,"Students");
DataTable students = ds.Tables["Students"];
DataRow studentRow = students.NewRow();
studentRow["ID"] = ID;
studentRow["Name"] = name;
studentRow["Gender"] = gender;
studentRow["TotalMarks"] = marks;
students.Rows.Add(studentRow);
adapter.Update(ds,"Students");
Now I want to edit a data row. The data will be change if the ID is matched with the ID parameter. This is the stored procedure I'm using:
create procedure updateStudent
#ID int,
#Name varchar(50),
#Gender varchar(10),
#TotalMarks int
AS
BEGIN
update Students set Name = #Name, Gender = #Gender, TotalMarks = #TotalMarks
where ID = #ID
END
and this is the C# code i use in the code behind:
int ID = int.Parse(TextBox1.Text);
string name = TextBox2.Text;
string gender = TextBox3.Text;
int marks = int.Parse(TextBox4.Text);
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlDataAdapter adapter = new SqlDataAdapter("Select * from Students",con);
DataTable dtStudents = new DataTable();
adapter.Fill(dtStudents);
SqlCommand cmd = new SqlCommand("updateStudent",con);
cmd.Parameters.Add("#ID", SqlDbType.Int, 0, "ID").Value = ID;
cmd.Parameters.Add("#Name", SqlDbType.NVarChar, 50, "Name").Value = name;
cmd.Parameters.Add("#Gender", SqlDbType.NVarChar, 10, "Gender").Value = gender;
cmd.Parameters.Add("#TotalMarks", SqlDbType.Int, 0, "TotalMarks").Value = marks;
adapter.UpdateCommand = cmd;
adapter.Update(dtStudents);
}
But after I clicked the Update button on my web form, there is no error message and the data didn't get updated in my database. What have I did wrong here?
I think you should write classes for executing stored procedures. It will be more easier to read and handle. RunQuery method in such a class like DB
private SqlConnection Connection;
public bool Open()
{
try
{
ConnectionString = "your connection string";
Connection = new SqlConnection(ConnectionString);
Connection.Open();
return true;
}
catch (Exception ex)
{
errorMessage = ex.Message;
return false;
}
}
public bool RunQuery(string ProcedureName, SqlParameter[] Parameters)
{
bool res = false;
try
{
SqlCommand Command = new SqlCommand();
Command.CommandText = ProcedureName;
Command.CommandType = CommandType.StoredProcedure;
Command.Connection = Connection;
Command.Parameters.AddRange(Parameters);
Command.ExecuteNonQuery();
res = true;
}
catch (Exception ex)
{
throw ex;
}
return res;
}
And you can call it
SqlParameter[] param= new SqlParameter[4];
param[0] = new SqlParameter("#ID", ID);
param[1] = new SqlParameter("#Name", name);
param[2] = new SqlParameter("#Gender", gender);
param[3] = new SqlParameter("#TotalMarks", marks);
RunQuery("updateStudent", param);

Error/exception handling (try-catch) C#

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).

Unable to insert data into MS Access database from Visual C#

just a beginner in Programing ...
I use a class to handle the connectionstring .
public class DataBase
{
public OleDbConnection con = new OleDbConnection();
public OleDbCommand cmd = new OleDbCommand();
public void getConnection()
{
con.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Project\Database\DataBase.mdb";
}
private void btnPrint_Click(object sender, EventArgs e)
{
DataBase db = new DataBase();
db.getConnection();
string Name = txtCostumerName.Text;
string DayorNight = cboSwimming.Text;
string Adult1 = txtAdultCount.Text;
string Kid = txtKidsCount.Text;
string Cottage1 = cboCottageType.Text;
string Room = cboRoomType.Text;
string Total1 = lblCottageTotal.Text;
string Cash1 = txtCashRecieve.Text;
string Change1 = txtChange.Text;
db.con.Open();
OleDbCommand command = new OleDbCommand ("INSERT INTO TicketAndCottage (Cotumer_Name , Swimming, Adult, Kids, Cottage, Room , Total, Cash, Change) Values(#Name , #DayorNight , #Adult1 ,#Kid , #Cottage1 , #Room, #Total1 , #Cash1 , #Change1)");
command.Connection = db.con;
command.CommandType = CommandType.Text;
if (db.con.State == ConnectionState.Open)
{
command.Parameters.Add("#Cotumer_Name", OleDbType.VarChar, 20).Value = Name;
command.Parameters.Add("#Swimming", OleDbType.VarChar, 20).Value = DayorNight;
command.Parameters.Add("#Adult", OleDbType.VarChar, 20).Value = Adult1;
command.Parameters.Add("#Kids", OleDbType.VarChar, 20).Value = Kid;
command.Parameters.Add("#Cottage", OleDbType.VarChar, 20).Value = Cottage1;
command.Parameters.Add("#Room", OleDbType.VarChar, 20).Value = Room;
command.Parameters.Add("#Total", OleDbType.VarChar, 20).Value = Total1;
command.Parameters.Add("#Cash", OleDbType.VarChar, 20).Value = Cash1;
command.Parameters.Add("#Change", OleDbType.VarChar, 20).Value = Change1;
try
{
command.ExecuteNonQuery();
MessageBox.Show("Data Added");
db.con.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
//db.con.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
and when i click the button i got "Microsoft JET Database Engine"
Without seeing more context (such as what your connection string and data context look like), I can only take a guess.
One issue appears to be a typo in the field below called "Cotumer_Name". Your text box is named "CostumerName" with an S in there.
OleDbCommand command = new OleDbCommand
("INSERT INTO TicketAndCottage (Cotumer_Name , Swimming, Adult, Kids, Cottage, Room , Total, Cash, Change)
Values(#Name , #DayorNight , #Adult1 ,#Kid , #Cottage1 , #Room, #Total1 , #Cash1 , #Change1)");
It'd be helpful to include some more code.
I figure out whats wrong
private void btnPrint_Click(object sender, EventArgs e)
{
DataBase db = new DataBase();
db.getConnection();
db.con.Open();
string Name = txtCostumerName.Text;
string DayorNight = cboSwimming.Text;
string Adult1 = txtAdultCount.Text;
string Kid = txtKidsCount.Text;
string Cottage1 = cboCottageType.Text;
string Room = cboRoomType.Text;
double Total1 = Convert.ToDouble(lblCottageTotal.Text);
double Cash1 = Convert.ToDouble(txtCashRecieve.Text);
double Change1 = Convert.ToDouble(txtChange.Text);
OleDbCommand command = new OleDbCommand("INSERT INTO TicketAndCottage (Costumer_Name , Swimming, Adult, Kids, Cottage, Room , Total, Cash, Change) Values(#Name , #DayorNight , #Adult1 ,#Kid , #Cottage1 , #Room, #Total1 , #Cash1 , #Change1)", db.con);
if (db.con.State == ConnectionState.Open)
{
command.Parameters.Add("#Costumer_Name", OleDbType.VarChar, 50).Value = Name;
command.Parameters.Add("#Swimming", OleDbType.VarChar, 50).Value = DayorNight;
command.Parameters.Add("#Adult", OleDbType.VarChar, 50).Value = Adult1;
command.Parameters.Add("#Kids", OleDbType.VarChar, 50).Value = Kid;
command.Parameters.Add("#Cottage", OleDbType.VarChar, 50).Value = Cottage1;
command.Parameters.Add("#Room", OleDbType.VarChar, 50).Value = Room;
command.Parameters.Add("#Total", OleDbType.Double, 50).Value = Total1;
command.Parameters.Add("#Cash", OleDbType.Double, 50).Value = Cash1;
command.Parameters.Add("#Change", OleDbType.Double, 50).Value = Change1;
try
{
command.ExecuteNonQuery();
db.con.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
// db.con.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}

Convert string to smalldatetime before a database insert

I have everything inserting fine until I try to insert a string "09/21/3013" into the ArrivalDate column which is a smalldatetime. How do I convert this so I can insert into the database? Thanks in advance!
Here's the code:
private void ExecuteInsert(string BookingName, string BookedBy)
{
string connString = System.Configuration.ConfigurationManager.ConnectionStrings["CateringAuthorizationEntities"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
string sql = "INSERT INTO tbBooking (BookingName, BookedBy, ArrivalDate) VALUES "
+ " (#BookingName, #BookedBy, #ArrivalDate)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[3];
//param[0] = new SqlParameter("#id", SqlDbType.Int, 20);
param[0] = new SqlParameter("#BookingName", System.Data.SqlDbType.VarChar, 50);
param[1] = new SqlParameter("#BookedBy", System.Data.SqlDbType.VarChar, 50);
param[2] = new SqlParameter("#ArrivalDate", System.Data.SqlDbType.SmallDateTime);
param[0].Value = BookingName;
param[1].Value = BookedBy;
param[2].Value = ArrivalDate;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void BtnCatering_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//call the method to execute insert to the database
ExecuteInsert(BookingName.Text, BookedBy.Text);
Response.Write("Record was successfully added!");
}
}
if (ArrivalDate != DBNull.Value)
param[2].Value = Convert.ToDateTime(ArrivalDate);
else
{
param[2].Value = // default value
}
You may try to use DateTime instead of String.
param[2].Value = Convert.ToDateTime(ArrivalDate);
Using DateTime.ParseExact will allow you to control the exact conversion of your date:
CultureInfo provider = CultureInfo.InvariantCulture;
param[2].Value = DateTime.ParseExact(ArrivalDate, "MM/dd/yyyy hh:mm:ss tt", provider);

Saving ID to database based on dropdown selection

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

Categories