Database dropdown list value printed on labels - c#

I'm using ASP.net to make a dropdown menu. The dropdown menu is linked to a database, all that works. If a value is selected in the dropdown, labels have to be filled that match the dropdown value in the database.
Hope I'm being clear, here's what I have so far :
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.Open();
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + Server.MapPath(#"\App_Data") + #"\JipEnJanneke.mdb";
OleDbCommand cmd1 = new OleDbCommand("Select (Prijs, Jaartal, ISBN) from JipEnJanneke where Titel = #Titel", conn);
cmd1.Parameters.AddWithValue("#Titel", DropDownList1.SelectedValue.ToString());
OleDbDataReader rd = cmd1.ExecuteReader();
while (rd.Read())
{
lbl_Prijs.Text = rd["Prijs"].ToString();
lbl_Jaar.Text = rd["Jaartal"].ToString();
lbl_Isbn.Text = rd["ISBN"].ToString();
}
conn.Close();
Unfortunately this leaves the labels empty. If I add the function to my page_load the labels do get filled, but for some reason only by the first value in the dropdown. A similair post on here suggested shoving it in the selectindexchanged, but that leaves it empty for me. Anyone got an idea?
Here's my page_load event right now
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + Server.MapPath(#"\App_Data") + #"\JipEnJanneke.mdb";
//conn.ConnectionString = "Provider=Microsoft.JET.OLEDB.4.0; Data Source=" + Server.MapPath(#"\App_Data") + #"\JipEnJanneke.mdb";
lblConnectionFeedback.Text = "";
try
{
conn.Open();
lblConnectionFeedback.Text += "Connection is: " + conn.State.ToString();
// HIER QUERY
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM Boeken";
OleDbDataReader rd = cmd.ExecuteReader();
DropDownList1.DataSource = rd;
DropDownList1.DataTextField = "Titel";
DropDownList1.DataValueField = "Titel";
DropDownList1.DataBind();
rd.Close();
conn.Close();
}
catch (Exception exc)
{
lblConnectionFeedback.Text = exc.Message;
}
finally
{
conn.Close();
lblConnectionFeedback.Text += "<br />Connection is: " + conn.State.ToString();
}

In your load event AND your code in the dropdown_selectedindexchanged, check the IsPostBack of the page. Ex :
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (IsPostBack){
OleDbConnection conn = new OleDbConnection();
conn.Open();
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + Server.MapPath(#"\App_Data") + #"\JipEnJanneke.mdb";
OleDbCommand cmd1 = new OleDbCommand("Select (Prijs, Jaartal, ISBN) from JipEnJanneke where Titel = #Titel", conn);
cmd1.Parameters.AddWithValue("#Titel", DropDownList1.SelectedValue.ToString());
OleDbDataReader rd = cmd1.ExecuteReader();
while (rd.Read())
{
lbl_Prijs.Text = rd["Prijs"].ToString();
lbl_Jaar.Text = rd["Jaartal"].ToString();
lbl_Isbn.Text = rd["ISBN"].ToString();
}
conn.Close();
}
}
Load :
if (!IsPostBack){
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + Server.MapPath(#"\App_Data") + #"\JipEnJanneke.mdb";
//conn.ConnectionString = "Provider=Microsoft.JET.OLEDB.4.0; Data Source=" + Server.MapPath(#"\App_Data") + #"\JipEnJanneke.mdb";
lblConnectionFeedback.Text = "";
try
{
conn.Open();
lblConnectionFeedback.Text += "Connection is: " + conn.State.ToString();
// HIER QUERY
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM Boeken";
OleDbDataReader rd = cmd.ExecuteReader();
DropDownList1.DataSource = rd;
DropDownList1.DataTextField = "Titel";
DropDownList1.DataValueField = "Titel";
DropDownList1.DataBind();
rd.Close();
conn.Close();
}
catch (Exception exc)
{
lblConnectionFeedback.Text = exc.Message;
}
finally
{
conn.Close();
lblConnectionFeedback.Text += "<br />Connection is: " + conn.State.ToString();
}
}

Please check that the AutoPostBack property of the DropDownList1 is set to True.

Related

C# multi valued combo box value to SQL Server database

private void filljobid()
{
try
{
string jobid = "";
int newjobid, oldjobid;
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand("SELECT MAX(job_id) FROM job", con);
SqlDataReader reader;
reader = cmd.ExecuteReader();
while (reader.Read())
{
jobid = reader[0].ToString();
}
oldjobid = int.Parse(jobid.ToString());
newjobid = oldjobid + 1;
jobidtextbox.Text = newjobid.ToString();
}
catch (Exception)
{
MessageBox.Show("Error while connecting");
}
}
private void fillcustomercombox()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("SELECT customer_id,(first_name + ' ' + last_name + ' - ' + contact) AS CUSTOMERNAME FROM customer", con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
customeridcombobox.DataSource = ds.Tables[0];
customeridcombobox.DisplayMember = "CUSTOMERNAME";
customeridcombobox.ValueMember = "customer_id";
cmd.ExecuteReader();
con.Close();
// CODE FOR DISPLAYING multiple values in another way, but not sure how to retrieve data from this function
// for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
// {
// customeridcombobox.Items.Add(ds.Tables[0].Rows[i][0] + " - " + ds.Tables[0].Rows[i][1] + " " + ds.Tables[0].Rows[i][2]);
// }
}
private void filldepotcombox()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("SELECT depot_id,(branch_name + ' - ' + region_name + ' - ' + location) AS DEPOTNAME FROM depot", con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
depotidcombobox.DataSource = ds.Tables[0];
depotidcombobox.DisplayMember = "DEPOTNAME";
depotidcombobox.ValueMember = "depot_id";
cmd.ExecuteReader();
con.Close();
}
private void filljobtypecombox()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True";
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("SELECT job_type FROM jobtype", con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
jobtypecombobox.DisplayMember = "job_type";
jobtypecombobox.ValueMember = "job_type";
jobtypecombobox.DataSource = ds.Tables[0];
cmd.ExecuteReader();
con.Close();
}
private void loadingcomboboxesdata_Load(object sender, EventArgs e)
{
fillcustomercombox();
filljobid();
filldepotcombox();
filljobtypecombox();
}
private void addnewjobbutton_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMoversDB;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into job (start_location, end_location, depot_id, job_type, customer_id,) values ('" + startlocationtxtbox.Text + "','" + endlocationtxtbox.Text + "','" + depotidcombobox.Text + "','" + jobtypecombobox.Text + "','" + customeridcombobox.Text + "')";
cmd.ExecuteReader();
con.Close();
MessageBox.Show("Added new job");
}
catch (Exception)
{
MessageBox.Show("ERROR: CANNOT CONNECT TO DATABASE");
}
}
What I'm trying to achieve is basically take the users selected value which is displayed in the combo box which is valuemember and then insert it into the database. Right now I get the error when I try to insert the data into the database. When I do the combo box with a single value it works fine but it doesn't work when I do it with multiple values.
Could someone close this question. I managed to solve my own question. I dont know if this solution is considered good but here you go.
private void addnewjobbutton_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-CCQ1T25;Initial Catalog=SmartMovers;Integrated Security=True"))
{
try
{
using (var cmd = new SqlCommand("INSERT INTO job(start_location, end_location, depot_id, job_type, customer_id) VALUES ('" + startlocationtxtbox.Text + "','" + endlocationtxtbox.Text + "',#3,#4, #5)"))
{
cmd.Connection = con;
//cmd.Parameters.AddWithValue("#1", startlocationtxtbox.SelectedText);
//cmd.Parameters.AddWithValue("#2", endlocationtxtbox.SelectedText);
cmd.Parameters.AddWithValue("#3", depotidcombobox.SelectedValue);
cmd.Parameters.AddWithValue("#4", jobtypecombobox.SelectedValue);
cmd.Parameters.AddWithValue("#5",customeridcombobox.SelectedValue);
con.Open();
if(cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
}
}
catch (Exception)
{
MessageBox.Show("ERROR: CANNOT CONNECT TO DATABASE");
}
}
}

prevent duplicate data from Excel to db via Oledb c#

I Have a excel and I want Upload only four columns of that to SQL Table with a button.
The problem is when I repeat click the button all of that data will be duplicated but I Don't want that. I want only new data to be update.
My query:
protected void Button1_Click(object sender, EventArgs e)
{
int UserID;
int InsuID;
string Result;
int Year;
//** مسیر فایل اکسل**
String ExcelPath = #"D:\Insu_lab.xlsx";
//** کانکشن به آفیس**
OleDbConnection mycon = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + ExcelPath + "; Extended Properties=Excel 8.0; Persist Security Info = False");
mycon.Open();
OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", mycon);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
UserID = Convert.ToInt32(dr[0].ToString());
InsuID = Convert.ToInt32(dr[1].ToString());
Result = dr[2].ToString();
Year = Convert.ToInt32(dr[3].ToString());
savedata(UserID, InsuID, Result, Year);
Label1.Text = "اطلاعات با موفقیت در دیتابیس ذخیره شد";
}
}
private void savedata(int UserID, int InsuID, string Result, int Year)
{
String query = "insert into tbl_Result(UserID,InsuID,Result,Year) values(" + UserID + ",'" + InsuID + "','" + Result + "','" + Year + "') ";
String mycon = "Data Source=MC6082; Initial Catalog=Insurance; Integrated Security=true";
SqlConnection con = new SqlConnection(mycon);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
Solution 1: When you clickedon button, that(button) disable the button.
Button1.disable = true;
When export ended:
Button1.disable = false;
Solution 2: you can use from jquery ajax in this part.

InvalidOperationException: Connection property has not been initialized in update command?

protected void btnUpdate_Click(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("update Students set RegNo='" + RegNo.Text + "',Name='" + Name.Text + "',Address=" + Address.Text);
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
//ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowSuccess", "javascript:alert('Record Updated Successfully');", true);
Response.Write("Record saved successfully");
}
Response.Redirect("~/WebForm1.aspx");
}
This code displays an error like this:
System.InvalidOperationException. ExecuteNonQuery: Connection property has not been initialized.
You need to tell your sql command that use this connection(con) to execute the command(cmd).so use an overloaded constructor of the SqlCommand class that takes 2 parameters(cmdText, connection).
SqlCommand cmd = new SqlCommand("update Students set RegNo='" +
RegNo"',Name='" + Name.Text + "',Address=" + Address.text, con);
But it is also possible, to create an instance of SqlCommand class using the parameter less constructor, and then later specify the command text and connection, using the CommandText and Connection properties of the SqlCommand object as shown below.
SqlCommand cmd = new SqlCommand("update Students set RegNo='" + RegNo.Text + "',Name='" + Name.Text + "',Address=" + Address.Text);
cmd.Connection = con;
con.Open();
You can use the using statement where the resources are automatically disposed.We don't have to explicitly call Close() method, when using is used. The connection will be automatically closed for us.
int result;
using (SqlConnection con = new SqlConnection(constr))
{
SqlCommand cmd = new SqlCommand("update Students set RegNo='" + RegNo.Text + "',Name='" + Name.Text + "',Address=" + Address.Text, con);
con.Open();
result = cmd.ExecuteNonQuery();
}
if (result == 1)
{
//ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowSuccess", "javascript:alert('Record Updated Successfully');", true);
Response.Write("Record saved successfully");
}
Response.Redirect("~/WebForm1.aspx");
To try to use as following sample code
string constr ="Data Source=localhost;Initial Catalog=test;Persist Security Info=True;User ID=sa;Password=1111"
SqlConnection con = new SqlConnection(constr);
I think , in the SQL Command you need to assign the connection
protected void btnUpdate_Click(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("update Students set RegNo='" + RegNo.Text + "',Name='" + Name.Text + "',Address=" + Address.Text);
cmd.Connection = con;
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
//ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowSuccess", "javascript:alert('Record Updated Successfully');", true);
Response.Write("Record saved successfully");
}
Response.Redirect("~/WebForm1.aspx");
}
string constr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("update Student set Name='" + Name.Text + "',Address='" + Address.Text + "'where RegNo=" + RegNo.Text);
cmd.Connection = con;//adding this line my error solved
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
I changed my code like above.

Error with SqlBulkCopyColumnMapping

I am able to import excel sheet data into sql server table but i am unable to implement column mapping. please help.
protected void Button1_Click(object sender, EventArgs e)
{
string strFileType = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
string strFileName = FileUpload1.PostedFile.FileName.ToString();
FileUpload1.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
string strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);
string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source="+strNewPath +"; Extended Properties=Excel 8.0;");
//string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=C:\\myFolder\\Book1.xls;" + "Extended Properties=Excel 8.0;");
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select ID,Data FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=DITSEC3;Initial Catalog=test;Integrated Security=True";
con.Open();
DataTable dt1 = new DataTable();
string s = "select count(*) from ExcelTable";
string r = "";
SqlCommand cmd1 = new SqlCommand(s, con);
try
{
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
da1.Fill(dt1);
}
catch { }
int RecordCount;
RecordCount = Convert.ToInt32(cmd1.ExecuteScalar());
r = RecordCount.ToString();
Label1.Text = r;
con.Close();
int prv = Convert.ToInt32(r);
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelTable";
bulkCopy.WriteToServer(dr);
con.Open();
SqlBulkCopyColumnMapping mapping1 = new SqlBulkCopyColumnMapping("id", "ida");
SqlBulkCopyColumnMapping mapping2 = new SqlBulkCopyColumnMapping("data", "dataa");
con.Close();
}
con.Open();
DataTable dt = new DataTable();
s = "select count(*) from ExcelTable"; r = "";
SqlCommand cmd = new SqlCommand(s, con);
try { SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
catch { }
RecordCount = Convert.ToInt32(cmd.ExecuteScalar());
r = RecordCount.ToString(); Label1.Text = r;
con.Close();
int ltr = Convert.ToInt32(r);
if (prv == ltr)
{
Label1.Text = "No records Added";
}
else
{
Label1.Text = "Records Added Successfully !";
}
}
}
Error:
No value given for one or more required parameters.
You created but didn't add the mappings to SqlBulkCopy.
Add the code below:
bulkCopy.ColumnMappings.Add(mapping1);
bulkCopy.ColumnMappings.Add(mapping2);

Fill DropDownList from database

I am new to C# and trying to populate a DropDownList based on a database value. I tried connecting to database as shown below - tested with the statement and it says connected. Can I assume this is correct? Am I on the right track? Also, how do I then select value from the table and fill DropDownList with a field?
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection (
"Data Source=.\\SQLEXPRESS;AttachDbFilename=C:customers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
try
{
connection.Open();
TextBox1.Text = "connected";
}
catch (Exception)
{
TextBox1.Text = " not connected";
}
}
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection (
"Data Source=.\\SQLEXPRESS;AttachDbFilename=C:customers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
try
{
SqlDataReader dReader;
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
cmd.CommandText ="Select distinct [Name] from [Names]" +
" order by [Name] asc";
connection.Open();
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
while (dReader.Read())
//Names collection is a combo box.
namesCollection.Add(dReader["Name"].ToString());
}
else
{
MessageBox.Show("Data not found");
}
dReader.Close()
TextBox1.Text = "connected";
}
catch (Exception)
{
TextBox1.Text = " not connected";
}
}
Hope that helps................
It's So Much Simple :----
SqlConnection con = new SqlConnection();
DataSet ds = new DataSet();
con.ConnectionString = #"Data Source=TOP7\SQLEXPRESS;Initial Catalog=t1;Persist Security Info=True;User ID=Test;Password=t123";
string query = "Select * from tbl_User";
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandText = query;
con.Open();
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
adpt.Fill(ds);
comboBox1.Items.Clear();
comboBox1.DisplayMember = "UserName";
comboBox1.ValueMember = "UserId";
comboBox1.DataSource = ds.Tables[0];
------------------------------------------------------------------------
using (SqlConnection con = new SqlConnection("Data Source = NIPOON; Initial Catalog = CustomerOrders; Integrated Security = true"))
{
SqlCommand cmd = new SqlCommand("SELECT Name FROM Customer", con);
con.Open();
dropDownList.DataSource = cmd.ExecuteReader();
dropDownList.DataTextField = "Name";
dropDownList.DataValueField = "Name";
dropDownList.DataBind();
}

Categories