i have 2 drop down lists and DB in my web application project. in the DB i have domain table and subDomain table. in the subDomain table i have foreign key to the column DomainId in domain table.
i populate the 1st droplist with data from domain (im using DomainId as datavalue and DomainName as datatext/ here is the code:
protected void Page_Load(object sender, EventArgs e)
{
string connString = System.Configuration.ConfigurationManager.ConnectionStrings["SampleConnectionString"].ToString();
conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("SELECT DomainId , DomainName FROM Domain",conn);
conn.Open();
DropDownList1.DataTextField = "DomainName";
DropDownList1.DataValueField = "DomainId";
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataBind();
}
now when the user select item from the droplist i want to populate the 2nd droplist according to the item that was selected, but its not working.
here is the 2nd part of code:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string connString = System.Configuration.ConfigurationManager.ConnectionStrings["SampleConnectionString"].ToString();
conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("SELECT SubDomainName, SubDomainId FROM SubDomain where DomainId= #id", conn);
cmd.Parameters.AddWithValue("#id", DropDownList1.SelectedValue);
conn.Open();
DropDownList2.DataTextField = "SubDomainName";
DropDownList2.DataValueField = "SubDomainId";
DropDownList2.DataSource = cmd.ExecuteReader();
DropDownList2.DataBind();
conn.Close();
}
Set AutoPostBack property of your DropDownList1 control to true. If you already set that, but still have an error, post your .aspx file also
Related
protected void CompanyDropDown_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
using (SqlConnection cn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("[dropdownCompany]", cn);
cn.Open();
CompanyDropDown.DataSource = cmd.ExecuteReader();
CompanyDropDown.DataBind();
}
}
The stored procedure dropdownCompany is just one column with a list of company names.
For some reason this is not populating the drop down when I execute the web form.
Before binding, specify DataTextField and DataValueField for the dropdown.
DataTextField and DataValueField should be the name of columns from the result set which you get after executing your stored procedure.
You should specify which field will be visible to the user in the dropdown. This will be your DataTextField.
DataValueField is not visible to the user. but you will need this value when you are performing some other operation based on the selected item in the dropdown.
CompanyDropDown.DataTextField = "Name";
CompanyDropDown.DataValueField = "ID";
CompanyDropDown.DataBind();
You will have to set the CommandType property of your SqlCommand object to CommandType.StoredProcedure
protected void CompanyDropDown_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
using (SqlConnection cn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("[dropdownCompany]", cn);
cmd.CommandType = CommandType.StoredProcedure;
cn.Open();
CompanyDropDown.DataSource = cmd.ExecuteReader();
CompanyDropDown.DataBind();
}
}
I have a dropdownlist that is populated with semesters. When the semester selection is changed, I want to populate another dropdownlist with courses available for that semester based on the semesterID. I have a stored procedure in SQL Server that gets courses based on the semesterId parameter. The semester list is populated just fine, but when I select a semester, I get an error while using the SP to get the courses. The error says Procedure or function 'GetCourses' expects parameter '#semesterId', which was not supplied. even though I supply the value for #semesterId before I open the connection. What am I doing wrong?
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
PopulateSemesterList();
}
private void PopulateSemesterList()
{
string connstring;
connstring = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
SqlConnection conn = new SqlConnection(connstring);
SqlCommand cmd = new SqlCommand("dbo.GetSemesters", conn);
conn.Open();
DDSemesters.DataSource = cmd.ExecuteReader();
DDSemesters.DataTextField = "semesterName";
DDSemesters.DataValueField = "semesterId";
this.DataBind();
conn.Close();
conn.Dispose();
DDSemesters.Items.Insert(0, new ListItem("Select Semester", "0"));
DDSemesters.SelectedIndex = 0;
}
protected void DDSemesters_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList DDSemesters = sender as DropDownList;
int selectedSemester = Convert.ToInt32(DDSemesters.SelectedItem.Value);
string connstring;
connstring = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
SqlConnection conn = new SqlConnection(connstring);
SqlCommand cmd = new SqlCommand("dbo.GetCourses", conn);
cmd.Parameters.Add(new SqlParameter("#semesterId", selectedSemester));
conn.Open();
DDCourses.DataSource = cmd.ExecuteReader();
DDCourses.DataTextField = "courseName";
DDCourses.DataValueField = "courseId";
this.DataBind();
conn.Close();
conn.Dispose();
DDCourses.Items.Insert(0, new ListItem("Select Course", "0"));
DDCourses.SelectedIndex = 0;
DDCourses.Visible = true;
CoursesLbl.Visible = true;
}
As far as I can tell your CommandType is the default, Text, which causes the CommandText to be interpreted as an SQL query instead of just a stored procedure name.
You'll want to set it to StoredProcedure instead:
cmd.CommandType = CommandType.StoredProcedure;
Alternatively you could make your command a full SQL query that properly passes the parameters to the stored procedure.
I have two table, called MEDICALCENTRE AND APPOINTMENT. For medicalcenter table, primary key is mcID and appointment table primary key is appointmentID. Both have this mcID field. I make the drop down list populate data from MEDICALCENTRE table, which have data inside which is 1, 3 and 4. After choosing the mcID I want, I click submit and it will get sent to appointment table mcID. The problem is Whether I choose 1, 3 or 4 in the drop down list, the value is always 1 on the mcID field, in the appointment table.
protected void Page_Load(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["sacpConnectionString"].ToString(); // connection string
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand("select * from MEDICALCENTRE", con); // table name
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds); // fill dataset
ddlMedicalCentre.DataTextField = ds.Tables[0].Columns["mcID"].ToString(); // text field name of table dispalyed in dropdown
ddlMedicalCentre.DataValueField = ds.Tables[0].Columns["mcID"].ToString(); // to retrive specific textfield name
ddlMedicalCentre.DataSource = ds.Tables[0]; //assigning datasource to the dropdownlist
ddlMedicalCentre.DataBind(); //binding dropdownlist
}
protected void btnCreate_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sacpConnectionString"].ConnectionString))
{
try
{
SqlCommand cmd = new SqlCommand();
Guid guid;
guid = Guid.NewGuid();
String strStatus = "waiting";
string sql = "INSERT INTO appointment (aStatus,aDate, aTime, aContact, aHeight, aWeight, patientID, mcID)";
sql += "VALUES (#aStatus, #aDate, #aTime, #aContact, #aHeight, #aWeight, #patientID, #mcID)";
cmd.Parameters.AddWithValue("#aStatus", strStatus);
cmd.Parameters.AddWithValue("#aDate", txtDate.Value);
cmd.Parameters.AddWithValue("#aTime", txtTime.Value);
cmd.Parameters.AddWithValue("#aContact", txtContact.Value.Trim());
cmd.Parameters.AddWithValue("#aHeight", txtHeight.Value.Trim());
cmd.Parameters.AddWithValue("#aWeight", txtWeight.Value.Trim());
cmd.Parameters.AddWithValue("#patientID", txtpatientID.Value.Trim());
cmd.Parameters.AddWithValue("#mcID", ddlMedicalCentre.SelectedValue);
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
cmd.ExecuteNonQuery();
// Session.Add("Username", txtFirstName.Value);
// Session.Add("Password", txtContact.Value);
// FormsAuthentication.SetAuthCookie(txtFirstName.Value, true);
Response.Redirect("../index.aspx");
}
finally
{
con.Close();
}
}
}
}
In your Page_Load method you don't check for the IsPostBack property, so your method is executed at every postback resetting the DropDown list to the first item
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
string constr = ConfigurationManager.ConnectionStrings["sacpConnectionString"].ToString();
SqlConnection con = new SqlConnection(constr);
con.Open();
......
}
}
I have a DropDownList that is linked to a SQL database. It currently shows a list of customers. I am trying to make it so that once a customer is selected, multiple textboxes are automatically filled (such as address, city, etc). I am able to automatically fill the "company name" textbox as the value is the one selected, but I do not know how to fill the other textboxes using the rest of the data in the row. How would I best go about doing this?
in .aspx:
<asp:DropDownList ID="DropDownList1" runat="server" ></asp:DropDownList>
C#:
DataTable customers = new DataTable();
...
SqlDataAdapter adapter = new SqlDataAdapter("SELECT CustomerName FROM Customers.dbo.Customer", connection);
adapter.Fill(customers);
DropDownList1.DataSource = customers;
DropDownList1.DataTextField = "CustomerName";
DropDownList1.DataValueField = "CustomerName";
DropDownList1.DataBind();
EDIT: Thanks Karl for your help. Follow his advice if you have a similar issue. Also, make sure to change the dropdownlist so it looks like:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" onselectedindexchanged="CompanyChanged"></asp:DropDownList>
EDIT2: For those that are having the same problem.. Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadOptions();
}
}
protected void LoadOptions()
{
DataTable customers = new DataTable();
SqlConnection connection = new SqlConnection(INSERT YOUR CONNECTION STRING HERE);
using (connection)
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT Column1 FROM Table", connection);
adapter.Fill(customers);
DropDownListID.DataSource = customers;
companyselect.DataTextField = "Column1";
companyselect.DataValueField = "Column1";
companyselect.DataBind();
}
}
protected void SelectionChanged(object sender, EventArgs e)
{
string selected= DropDownListID.SelectedItem.Value;
SqlConnection connection = new SqlConnection(YOUR CONNECTION STRING);
using (connection)
{
SqlCommand command = new SqlCommand("SELECT * FROM Table WHERE Column1= #Column1", connection);
command.Parameters.AddWithValue("#Column1", selected);
command.CommandType = CommandType.Text;
connection.Open();
SqlDataReader reader = command.ExecuteReader();
using (reader)
{
if (reader.HasRows)
{
reader.Read();
//add as many as needed to fill your textboxes
TextBox1.Text = reader.GetString(1);
TextBox2.Text = reader.GetString(2);
TextBox3.Text = reader.GetString(3);
}
else { }
}
}
}
And this is what my dropdownlist looks like:
<asp:DropDownList ID="DropDownListID" runat="server" AutoPostBack="true" onselectedindexchanged="SelectionChanged"></asp:DropDownList>
I would highly recommend that you use the CustomerID or equivalent ID field in the database as the DataValueField in your drop down list, as you may want to allow the same customer name in the database, but be able to tell them apart by ID.
Instead, try this:
SqlDataAdapter adapter = new SqlDataAdapter("SELECT CustomerName, CustomerID FROM Customers.dbo.Customer", connection);
adapter.Fill(customers);
DropDownList1.DataSource = customers;
DropDownList1.DataTextField = "CustomerName";
DropDownList1.DataValueField = "CustomerID";
DropDownList1.DataBind();
Note: Change CustomerID to whatever the actual ID column name in your database table actually is.
Now in your drop down list's SelectedIndexChanged event, grab the ID of the selected item and query the database for the single row of data, like this:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedID = DropDownList1.SelectedItem.Value;
SqlCommand theCommand = new SqlCommand("SELECT * FROM Customers.dbo.Customer WHERE CustomerID = #CustomerID", connection);
theCommand.Paramters.AddWithValue("#CustomerID", selectedId);
theCommand.CommandType = CommandType.Text;
using (SqlDataReader theReader = theCommand.ExecuteReader())
{
if (theReader.HasRows)
{
// Get the first row
theReader.Read();
// Set the text box values
CustomerName.Text = theReader.GetString(0);
...
}
}
}
Note: The retrieval of the single row of customer data uses a parameterized query to avoid SQL Injection vulnerabilities. Also, the code above uses the SqlCommand and SqlDataReader along with using blocks to properly dispose of the reader object.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
SQLconn.Open();
string req = "select distinct CapaciteTotal from Avion where NomAvion=" + DropDownList1.Text + "";
SqlCommand com = new SqlCommand(req, SQLconn);
SqlDataReader dr = com.ExecuteReader();
if (dr.Read())
{
TextBox1.Text = dr.GetValue(1).ToString();
if (DropDownList4.Text == "Aller Retour")
{
TextBox2.Text = dr.GetValue(1).ToString();
}
}
}
catch(Exception ex)
{
HttpContext.Current.Response.Write("<script>alert('Probleme de la base de donnee : " + ex.Message + "')</script>");
}
finally
{
SQLconn.Close();
}
}
i am using asp.net C# SQL to create a webpage.I need to list out a courseID to let user choose, but it list out two time same value in dropdownlist
S1111
S2222
S3333
S1111
S2222
S3333
,someone help
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn;
SqlDataReader dtr;
SqlCommand cmd;
string Connnection = ConfigurationManager.ConnectionStrings["ELearing"].ConnectionString;
conn = new SqlConnection(Connnection);
if (!Page.IsPostBack)
{
//Get Staff Information
conn.Open();
string cmdString = "SELECT DISTINCT CourseID FROM Schedule WHERE(StaffID = #scheduleStaffID)";
cmd = new SqlCommand(cmdString, conn);
cmd.Parameters.AddWithValue("#scheduleStaffID", Session["UserID"].ToString());
dtr = cmd.ExecuteReader();
while (dtr.Read())
{
ddlCourse.Items.Add(dtr["CourseID"].ToString());
}
dtr.Close();
conn.Close();
}
}
Try these
1.Do you get duplicates when you do externally SELECT DISTINCT CourseID FROM Schedule WHERE StaffId = 1
2.use breakpoints to check additional post backs.
3.Try ddlCourse.Items.Clear just before your while loop.