Unable to insert data into MS Access database from Visual C# - 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");
}
}

Related

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

i have issue in inserting date in ms access using c#

I m sorry if this question asked before, i am new to c# i am working with ms access database i am storing date to ms access date field...
please check what is the error
My error string is following:
failed to convert parameter value from a string to a timespan
The code is:
private void button1_Click(object sender, EventArgs e)
{
//create connection
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=posv.accdb";
conn.Open();
string Expanse_Name = expanse_name.Text;
string Expanse_Cost = expanse_cost.Text;
string Expanse_Date = expanse_date.Value.ToString("m/d/Y");
OleDbCommand cmd = new OleDbCommand("INSERT INTO expanses (Expanse_Name, Expanse_Cost,Expanse_Date) VALUES (#Expanse_Name, #Expanse_Cost,#Expanse_Date)", conn);
if(conn.State == ConnectionState.Open){
cmd.Parameters.Add("#Expanse_Name", OleDbType.VarChar, 20).Value = Expanse_Name;
cmd.Parameters.Add("#Expanse_Cost", OleDbType.UnsignedInt, 20).Value = Expanse_Cost;
cmd.Parameters.Add("#Expanse_Date", OleDbType.VarChar, 20).Value = Expanse_Date.;
try {
cmd.ExecuteNonQuery();
MessageBox.Show("Expanse Added Success fully!");
}catch(OleDbException exps){
MessageBox.Show(exps.Message);
conn.Close();
} // end try
} //end conn state
} // end save function
You need to specify the right datatype for the db variable. It depends what datatype you've chosen in db. So best approach is look at the respective datatype in the database and change it accordingly.
try this:
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=posv.accdb";
conn.Open();
string Expanse_Name = expanse_name.Text;
string Expanse_Cost = expanse_cost.Text;
string Expanse_Date = expanse_date.Value.ToString("m/d/Y");
OleDbCommand cmd = new OleDbCommand("INSERT INTO expanses (Expanse_Name, Expanse_Cost,Expanse_Date) VALUES (#Expanse_Name, #Expanse_Cost,#Expanse_Date)", conn);
if(conn.State == ConnectionState.Open){
cmd.Parameters.Add("#Expanse_Name", OleDbType.VarChar, 20).Value = Expanse_Name;
cmd.Parameters.Add("#Expanse_Cost", OleDbType.UnsignedInt, 20).Value = Expanse_Cost;
cmd.Parameters.Add("#Expanse_Date", OleDbType.DBTimeStamp, 20).Value = Expanse_Date.;
try {
cmd.ExecuteNonQuery();
MessageBox.Show("Expanse Added Success fully!");
}catch(OleDbException exps){
MessageBox.Show(exps.Message);
conn.Close();
} // end try
} //end conn state
}
Change the ToString format on the line line:
string Expanse_Date = expanse_date.Value.ToString("HH:mm:ss.fff");
I think the Expanse_Date should be keep in DateTime and the parameter type for it should be OleDbType.DBTimeStamp. (And please use using blocks.)
private void button1_Click(object sender, EventArgs e)
{
using (var conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=posv.accdb"))
{
conn.Open();
var Expanse_Name = expanse_name.Text;
var Expanse_Cost = expanse_cost.Text;
var Expanse_Date = expanse_date.Value;
using (var cmd = new OleDbCommand("INSERT INTO expanses (Expanse_Name, Expanse_Cost,Expanse_Date) VALUES (#Expanse_Name, #Expanse_Cost,#Expanse_Date)", conn))
{
cmd.Parameters.Add("#Expanse_Name", OleDbType.VarChar, 20).Value = Expanse_Name;
cmd.Parameters.Add("#Expanse_Cost", OleDbType.UnsignedInt, 20).Value = Expanse_Cost;
cmd.Parameters.Add("#Expanse_Date", OleDbType.DBTimeStamp, 20).Value = Expanse_Date;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Expanse Added Success fully!");
}
catch (OleDbException exps)
{
MessageBox.Show(exps.Message);
conn.Close();
}
}
}
}

I am trying to insert data in Access DB as per selection

Please find attached, my code which i have written, but when it runs and when i enter data in form n click on Submit it gives me error in "Command.executenonquery statement"..
It displays Invalid Operation exception was mishandled
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked == true)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\databses\electric_data.accdb";
OleDbCommand command = new OleDbCommand();
command.CommandText = "INSERT INTO Electric_Data (Asset_Id,Asset_Name,Emp_Id,Type_of_Asset,Actual_Start_date) VALUES (?,?,?,?,?)";
command.Parameters.Add("#Asset_Id", OleDbType.VarChar, 20).Value = textBox1.Text;
command.Parameters.Add("#Asset_Name", OleDbType.Char, 20).Value = textBox2.Text;
command.Parameters.Add("#Type_of_Asset", OleDbType.VarChar, 20).Value = textBox3.Text;
command.Parameters.Add("#Emp_Id", OleDbType.Char, 20).Value = textBox4.Text;
command.Parameters.Add("#Actual_Start_date", OleDbType.Date).Value = DateTime.Now;
command.ExecuteNonQuery();
conn.Open();
command.Connection = conn;
MessageBox.Show("Entry Registered Successfully.");
}
if (radioButton2.Checked == true)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\databses\electric_data.accdb";
OleDbCommand command = new OleDbCommand();
command.CommandText = "INSERT INTO Electric_Data (Asset_Id,Asset_Name,Emp_Id,Type_of_Asset,Actual_end_date) VALUES (?,?,?,?,?)";
command.Parameters.Add("#Asset_Id", OleDbType.VarChar, 20).Value = textBox1.Text;
command.Parameters.Add("#Asset_Name", OleDbType.Char, 20).Value = textBox2.Text;
command.Parameters.Add("#Emp_Id", OleDbType.VarChar, 20).Value = textBox3.Text;
command.Parameters.Add("#Type_of_Asset", OleDbType.VarChar, 20).Value = textBox4.Text;
command.Parameters.Add("#Actual_end_date", OleDbType.Date).Value = DateTime.Now;
command.ExecuteNonQuery();
conn.Open();
command.Connection = conn;
MessageBox.Show("Entry Registered Successfully.");
}
else if (radioButton1.Checked == false && radioButton2.Checked == false)
MessageBox.Show("Check Work_Start or Work_Complete option for successful Entry.");
}
}
}
You have gotten the conn.Open() in the wrong place. Try -->
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\databses\electric_data.accdb";
OleDbCommand command = new OleDbCommand();
command.CommandText = "INSERT INTO Electric_Data (Asset_Id,Asset_Name,Emp_Id,Type_of_Asset,Actual_Start_date) VALUES (#Asset_Id,#Asset_Name,#Emp_Id,#Type_of_Asset,#Actual_end_date)";
command.Parameters.Add("#Asset_Id", OleDbType.VarChar, 20).Value = textBox1.Text;
command.Parameters.Add("#Asset_Name", OleDbType.Char, 20).Value = textBox2.Text;
command.Parameters.Add("#Emp_Id", OleDbType.VarChar, 20).Value = textBox3.Text;
command.Parameters.Add("#Type_of_Asset", OleDbType.VarChar, 20).Value = textBox4.Text;
command.Parameters.Add("#Actual_end_date", OleDbType.Date).Value = DateTime.Now;
// Open connection and assign to command
conn.Open();
command.Connection = conn;
// Execute non-query command
command.ExecuteNonQuery();
As an aside:
you need to not duplicate conn strings, column names etc in your code. Makes for a nightmare to maintain and debug.
You need to add in try...catch exception handling - what if the DB doesn't open for some reason.
EDIT: command.CommandText as wrong also per answer by other learned people.
Your command text is completely wrong.Change question marks with your parameter names:
command.CommandText = "INSERT INTO Electric_Data (Asset_Id,Asset_Name,Emp_Id,Type_of_Asset,Actual_Start_date) VALUES (#Asset_Id,#Asset_Name,#Emp_Id,#Type_of_Asset,#Actual_end_date)";
You are open your connection after your ExecuteNonQuery, first open your connection,then execute your query
conn.Open();
command.Connection = conn;
command.ExecuteNonQuery();
Try this insert query.Remove ?,?,?,?
command.CommandText = "INSERT INTO Electric_Data (Asset_Id,Asset_Name,Emp_Id,Type_of_Asset,Actual_Start_date) VALUES (#Asset_Id,#Asset_Name,#Emp_Id,#Type_of_Asset,#Actual_end_date)";
check the datatypes of your table-columns

Trying to Insert Values into a Database from TextBoxes

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.

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