This was working the other day, not sure what happened but it isn't now and I cant figure it out. The label will only give me one item out of around 20(give or take) distinct items. No matter what I select in my drop down list, it always gives me that same value on the label.
HTML:
<td>
<asp:DropDownList ID="ddlCompanyCode" runat="server" CssClass="Dropdown" AutoPostBack="True" OnSelectedIndexChanged="ddlCompanyCode_SelectedIndexChanged" Width="139px" DataSourceID="CompanyCodeDS" DataTextField="CompanyCode" DataValueField="CompanyCode"></asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="ddlCompanyCode" Display="Dynamic" ErrorMessage="*Please select a drop down list item." ForeColor="#CC0000" ValidationGroup="Submit"></asp:RequiredFieldValidator>
</td>
<td>
<asp:Label ID="lblSourceSyst" runat="server" CssClass="txtLabel" Text="Select Company Code" Width="137px" ></asp:Label>
</td>
<asp:SqlDataSource ID="CompanyCodeDS" runat="server" SelectCommandType="StoredProcedure" ConnectionString="<%$ ConnectionStrings:RptDatamartConnectionString %>" SelectCommand="[AXMap].[SelectCompanyCode_GLSourceCOA]">
</asp:SqlDataSource>
C#:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlCompanyCode.Items.Add(new ListItem("--Please Select--", ""));
ddlCompanyCode.AppendDataBoundItems = true;
}
}
protected void ddlCompanyCode_SelectedIndexChanged(object sender, EventArgs e)
{
String connectionString = ConfigurationManager.ConnectionStrings["RptDatamartConnectionString"].ConnectionString;
String sqlStoredProc = "RptDatamart.AXMap.SelectCompanyCode_GLSourceCOA";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("#CompanyCode", ddlCompanyCode.SelectedItem.Value);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = sqlStoredProc;
cmd.Connection = con;
try
{
con.Open();
SqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
lblSourceSyst.Text = dataReader["SourceSystem"].ToString();
}
}
catch (Exception ex)
{
lblStatus.Text = ex.Message;
}
}
And then the stored procedure im trying to use...
ALTER PROCEDURE [AXMap].[SelectCompanyCode_GLSourceCOA]
#CompanyCode varchar(10) = Null,
#SourceSystem nvarchar(255) = Null
AS
BEGIN
SET NOCOUNT OFF;
Select distinct CompanyCode, SourceSystem from [RptDatamart].[AXMap].[GLSourceCOA]
END
my sql might be terribly off, but i would think it would work.
lblSourceSyst.Text = dataReader["SourceSystem"].ToString();
Should be:
lblSourceSyst.Text += dataReader["SourceSystem"].ToString();
Related
I have created two individual form and store data in one table but problem is that data store individually row ? I want to store data in one row.
and then i created two individual form and store data in one table and my data is store individually row that is issue?
table name: manager
Database fieldname:
- managerid int pk autoincrement
- firstname varchar(50)
- lastname varchar(50)
- address varchar(50)
- permanantaddress varchar(50)
- mno int
- experiance int
- currentcompanyname varchar(50)
- previouscompanyname varchar(50)
- currentsalary int
- expectedsalary int
Registrationform.aspx
<div>
FirstName: <asp:TextBox ID="txtfname" runat="server"></asp:TextBox>
<br />
lastName: <asp:TextBox ID="txtlname" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Insert" OnClick="Button1_Click" />
</div>
Registrationform.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
string query = "Insert into manager (firstname,lastname) values(#firstname,#lastname)SELECT SCOPE_IDENTITY()";
SqlCommand cmd = new SqlCommand(query, cn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#firstname", txtfname.Text);
cmd.Parameters.AddWithValue("#lastname",txtlname.Text);
cn.Open();
int? primaryKey = Convert.ToInt32(cmd.ExecuteScalar());
this.Session["primaryKey"] = primaryKey;
if(primaryKey != null)
{
Response.Redirect("Contactus.aspx");
}
cmd.ExecuteNonQuery();
cn.Close();
}
Contactus.aspx
Address:
<asp:TextBox ID="txtadd" runat="server"></asp:TextBox>
<br />
PermanantAddress:
<asp:TextBox ID="txtperaddress" runat="server"></asp:TextBox>
<br />
Mno:
<asp:TextBox ID="txtmno" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Insert" OnClick="Button1_Click" />
Contactus.aspx.cs
string sessionvariable;
protected void Page_Load(object sender, EventArgs e)
{
sessionvariable = Session["primaryKey"].ToString();
}
protected void Button1_Click(object sender, EventArgs e)
{
string query = "update manager set address=#address,permanantaddress=#permanantaddress,mno=#mno where managerid=#managerid";
SqlCommand cmd = new SqlCommand(query, cn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#address", txtadd.Text);
cmd.Parameters.AddWithValue("#permanantaddress", txtperaddress.Text);
cmd.Parameters.AddWithValue("#mno", txtmno.Text);
cn.Open();
if (sessionvariable != null)
{
**here give an error System.Data.SqlClient.SqlException: Must declare the scalar variable "#managerid"**
cmd.ExecuteNonQuery();
}
cn.Close();
}
I want to store data in one row.
see my watch window Image:
my problem is that datastore in individually row that is my problem?
enter image description here
Give an Error: here give an error System.Data.SqlClient.SqlException: Must declare the scalar variable "#managerid"
try this
string sessionvariable;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
sessionvariable = Session["primaryKey"].ToString();
string query = "update manager set address=#address,permanantaddress=#permanantaddress,mno=#mno where managerid=#managerid";
SqlCommand cmd = new SqlCommand(query, cn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#address", txtadd.Text);
cmd.Parameters.AddWithValue("#permanantaddress", txtperaddress.Text);
cmd.Parameters.AddWithValue("#mno", txtmno.Text);
cn.Open();
if (sessionvariable != null)
{
**here give an error System.Data.SqlClient.SqlException: Must declare the scalar variable "#managerid"**
cmd.ExecuteNonQuery();
}
cn.Close();
}
Read More
I have been following the following example to create some cascading dropdowns in a web application. The example does not use jquery and I would like to stick with this for now.
https://www.aspsnippets.com/Articles/Populate-Cascading-DropDownList-from-Database-in-ASPNet-Example.aspx
I am having trouble getting my second dropdown to populate a list using the result from the first. Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CategorySelect.Items.Clear();
CategorySelect.Items.Add(new ListItem("--Select Activity--", ""));
CategorySelect.AppendDataBoundItems = true;
String strConnString = ConfigurationManager
.ConnectionStrings["iSAMSConnectionString"].ConnectionString;
String strQuery = "select TblActivityManagerFolderID, txtName from dbo.TblActivityManagerFolder";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
CategorySelect.DataSource = cmd.ExecuteReader();
CategorySelect.DataTextField = "txtName";
CategorySelect.DataValueField = "TblActivityManagerFolderID";
CategorySelect.DataBind();
}
finally
{
con.Close();
con.Dispose();
}
}
}
protected void ActivitySelect_SelectedIndexChanged(object sender, EventArgs e)
{
ActivitySelect.Items.Clear();
ActivitySelect.Items.Add(new ListItem("--Select Activity--", ""));
ActivitySelect.AppendDataBoundItems = true;
String strConnString = ConfigurationManager
.ConnectionStrings["iSAMSConnectionString"].ConnectionString;
String strQuery = "select txtName, TblActivityManagerGroupID from dbo.TblActivityManagerGroup " +
"where intFolder=#txtName";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("#txtName",
CategorySelect.SelectedItem.Value);
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
ActivitySelect.DataSource = cmd.ExecuteReader();
ActivitySelect.DataTextField = "txtName";
ActivitySelect.DataValueField = "TblActivityManagerGroupID";
ActivitySelect.DataBind();
if (ActivitySelect.Items.Count > 1)
{
ActivitySelect.Enabled = true;
}
else
{
ActivitySelect.Enabled = false;
}
}
finally
{
con.Close();
con.Dispose();
}
}
I am using 2 tables.
TblActivityManagerFolder where I am using 2 fields - TblActivityManagerFolderID and txtName
TblActivityManagerGroup where I am using 2 fields - intFolder (which joins to TblActivityManagerFolderID) and txtName
My first drop down populates exactly as expected, but when I make a selection nothing at all happens in the 2nd dropdown.
Additional Code:
<asp:SqlDataSource ID="iSAMS" runat="server" ConnectionString="<%$ ConnectionStrings:iSAMSConnectionString %>"
SelectCommand="SELECT [blnActive], [TblActivityManagerFolderID], [txtName] FROM [TblActivityManagerFolder] WHERE ([intActivity] = #intActivity)">
<SelectParameters>
<asp:Parameter DefaultValue="34" Name="intActivity" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</div>
<div class="auto-style18">
<asp:DropDownList ID="CategorySelect" runat="server" DataTextField="txtName" DataValueField="TblActivityManagerFolderID"
OnSelectedIndexChanged="ActivitySelect_SelectedIndexChanged" CssClass="newStyle1">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="CategorySelect"
ErrorMessage="Please select your answer" style="text-align: left; font-weight: 700; color: #FF0000; font-size: medium;">!</asp:RequiredFieldValidator>
</div>
<br />
<div class="auto-style19">
<div class="auto-style20">
Please select the activity undertaken from the pick list:
<asp:DropDownList ID="ActivitySelect" runat="server" DataSourceID="iSAMSActivity" DataTextField="txtName" DataValueField="TblActivityManagerGroupId" CssClass="newStyle1" OnSelectedIndexChanged="ActivitySelect_SelectedIndexChanged">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="ActivitySelect"
ErrorMessage="Please select your answer" style="text-align: left; font-weight: 700; color: #FF0000; font-size: medium;">!</asp:RequiredFieldValidator>
<asp:SqlDataSource ID="iSAMSActivity" runat="server" ConnectionString="<%$ ConnectionStrings:iSAMSConnectionString %>" SelectCommand="SELECT [txtName], [intActivity], [intFolder], [TblActivityManagerGroupId] FROM [TblActivityManagerGroup] WHERE ([intFolder] = #intFolder)">
<SelectParameters>
<asp:ControlParameter ControlID="CategorySelect" Name="intFolder" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
I am also posting back the results so I can see if this is working using:
protected void Button1_Click(object sender, EventArgs e)
{
var activity = CategorySelect.DataTextField;
var CoCActivity = ActivitySelect.DataTextField;
var OtherSkills = SkillsTextBox.Text;
var ExtraDev = DevTextBox.Text;
var OtherActivities = OtherActivitiesTextBox.Text;
OutputLabel.Text = activity + "<br/>" + CoCActivity + "<br/>" + OtherSkills + "<br/>" + ExtraDev + "<br/>" + OtherActivities;
}
When it is posting back, it is producing an integer rather than the label in the dropdown list. Can this be changed so it post backs the actual text?
Set the AutoPostBack property of the DropdownList to True. If you dont set it, the event would be only be triggered server side when other events force a postback (a button click or similar)
I need to get products based on chosen subcategory. Now, it displays all products. How to do this? Here is my code. How to pass Subcategory.Id in button click?
...
<td>Subcategory</td>
<td>
<asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="SqlDataSource2" DataTextField="Name" DataValueField="Id">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2"
runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [Id], [Name] FROM [SubCategory] WHERE ([IdCategory] = #IdCategory)">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="IdCategory" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</td>
</tr>
<tr>
<td>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</td>
</tr>
...
protected void Button1_Click(object sender, EventArgs e)
{
...
SqlCommand command = new SqlCommand("SELECT productName, quantity, price FROM Product JOIN SubCategory ON Product.id_subcategory = SubCategory.id", _connection);
...
}
I'm gonna assume that the DropDownList2 control already contains the subcategory data.
You can get your subcategory ID in Button1_Click event with
DropDownList2.SelectedValue
Assuming that you have the following database table structure:
Product
- Id (PK)
- ProductName
- Quantity
- Price
- MainCatID (FK)
- SubCatID (FK)
- others...
Category
- Id (PK)
- Name
SubCategory
- Id (PK)
- Name
- IdCategory (FK)
Make sure to add the namespace System.Configuration so that you can access your connection string from your web.config file.
Instantiate an SqlConnection class to identify the database connection:
Create methods to display the list of categories and sub categories from their respective drop down list controls
Include an AutoPostBack property to DropDownList1 then set to true so that each time you select an item from the list, it will 'regenerate' a list of sub categories based from the selected category value.
Create an OnSelectedIndexChanged event of DropDownList1 calling the DisplaySubCategories() method.
Create a method that will display list of products based from selected category and sub category values
Include similar process from Step #4 to DropDownList2
Call the two methods inside the page load event.
SqlConnection con = new SqlConnection(ConfigurationManager.
ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DisplayCategories();
DisplaySubCategories();
}
}
void DisplayCategories()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT Id, Name FROM Category";
SqlDataReader data = cmd.ExecuteReader();
DropDownList1.DataSource = data;
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "Id";
DropDownList1.DataBind();
con.Close();
}
void DisplaySubCategories(string ID)
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT Id, Name FROM SubCategory WHERE IdCategory = #IdCategory";
cmd.Parameters.AddWithValue("#IdCategory", ID);
SqlDataReader data = cmd.ExecuteReader();
DropDownList2.DataSource = data;
DropDownList2.DataTextField = "Name";
DropDownList2.DataValueField = "Id";
DropDownList2.DataBind();
con.Close();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
DisplaySubCategories(DropDownList2.SelectedValue);
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
DisplayProducts(DropDownList1.SelectedValue, DropDownList2.SelectedValue);
}
void DisplayProducts(string mainCatID, string subCatID)
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = #"SELECT productName, quantity, price FROM Product
WHERE MainCatID = #MainCatID AND SubCatID=#SubCatID";
cmd.Parameters.AddWithValue("#MainCatID", mainCatID);
cmd.Parameters.AddWithValue("#SubCatID", subCatID);
SqlDataReader data = cmd.ExecuteReader();
string result = string.Empty;
while (data.Read())
{
result += "Name = " + Convert.ToString(reader["productName"]) + "; ";
result += "Quantity = " + Convert.ToString(reader["quantity"]) + "; ";
result += "Price = " + Convert.ToString(reader["price"]);
result += "<br />";
}
ReadAllOutput.Text = result;
con.Close();
}
.aspx
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" />
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged" />
I removed all the existing SqlDataSource controls because I find them messy.
Update:
You can also declare the method DisplayProducts() inside the Button click event
protected void Button1_Click(object sender, EventArgs e)
{
DisplayProducts(DropDownList1.SelectedValue, DropDownList2.SelectedValue);
}
PS: Some syntax might be incorrect (case-sensitivity) and I'm not using an IDE as of the moment.
I have a textbox whose values goes into the dropdown on button click. The problem is that when I fill all the data and submit the form. And when I come second time to see that value it disappears from the dropdown. What should I do to make the value gets in the dropdown fix. Please see the code for your reference:
<tr>
<td class="td">Location/City</td>
<td>
<asp:DropDownList CssClass="txtfld-popup" ID="ddlLocation" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlLocation_SelectedIndexChanged"></asp:DropDownList>
<asp:RequiredFieldValidator CssClass="error_msg" ID="reqLocation" ControlToValidate="ddlLocation" runat="server" ErrorMessage="Please enter location" InitialValue="--Select--" SetFocusOnError="true"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtOtherCity" runat="server" Visible="false" CssClass="txtfld-popup"></asp:TextBox>
<asp:Button ID="btnAddDropDown" runat="server" Width="63" Text="Add" CausesValidation="false" OnClick="btnAddDropDown_Click1" />
</td>
</tr>
Also, see the code behind for your reference:-
protected void ddlLocation_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlLocation.SelectedItem.Text == "Other")
{
txtOtherCity.Visible = true;
}
else
{
txtOtherCity.Visible = false;
}
}
protected void btnAddDropDown_Click1(object sender, EventArgs e)
{
string city = txtOtherCity.Text.Trim();
if (!string.IsNullOrEmpty(city))
{
ddlLocation.Items.Add(new ListItem(city, city));
}
}
You have to store the values from the textbox into the table dbo.Cities in database. Next time when you will come back to the same page then dropdown will fetch data from db.
Then on btnAddDropDown_Click1() you should insert the value of the city from the 'txtOtherCity' TextBox to the respective table, and then bind the DropDown of the city again. Something Like
protected void btnAddDropDown_Click1(object sender, EventArgs e)
{
string strconnection = System.Configuration.ConfigurationManager.AppSettings["YourConnectionString"].ToString();
string city = txtOtherCity.Text.Trim();
DataSet ds=new DataSet();
if (!string.IsNullOrEmpty(city))
{
// Your code to insert the value of the city from the 'txtOtherCity' `TextBox` to the respective table
//Edit: this is a very rudimentary code
string query = "INSERT INTO Career.Location (State) " +
"VALUES (#city) ";
// create connection and command
using(SqlConnection cn = new SqlConnection(strconnection))
using(SqlCommand cmd = new SqlCommand(query, cn))
{
// define parameters and their values
cmd.Parameters.Add("#city", SqlDbType.VarChar, 50).Value = city;
// open connection, execute INSERT, close connection
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
query = "select State from Career.Location";
using(SqlConnection cnn = new SqlConnection(strconnection))
using(SqlCommand cmdd = new SqlCommand(query, cnn))
{
SqlDataAdapter adp = new SqlDataAdapter(cmdd);
cnn.Open();
adp .Fill(ds);
cnn.Close();
}
ddlLocation.DataSource=ds;
ddlLocation.DataTextField = "State";
ddlLocation.DataValueField = "State";
ddlLocation.DataBind();
}
}
Do you have functionality of inserting the data in the DB (not only adding the new item in the drop down list). You have to insert the city in the appropriate table to be able to see it later on.
The implementation depends on your architecture, the implementation of the DAL etc.
For example - if you are using ADO.NET, you can insert the values in the table with a stored procedure:
CREATE PROCEDURE Add_City
#CityName varchar(50),
#StateID int
AS
BEGIN
INSERT INTO dbo.Cities (CityName, StateID) values (#CityName, #StateID)
END
GO
And then call it from the app. Something like that:
using (SqlConnection con = new SqlConnection("the connection string"))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Add_City";
cmd.Parameters.Add("#CityName", SqlDbType.VarChar).Value = txtCity.Text.Trim();
cmd.Parameters.Add("#StateID", SqlDbType.Int).Value = CountryId;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
// lblMessage.Text = "City inserted successfully!";
}
catch (Exception ex)
{
throw ex; // Or log or handle somehow the exception
}
}
I got the answer for this solution, Please see the code for your reference:-
protected void BindContrydropdown()
{
//conenction path for database
//string connection = WebConfigurationManager.ConnectionStrings["myconn"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select Id,CityName From Career.Location", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddllocation1.DataSource = ds;
ddllocation1.DataTextField = "CityName";
ddllocation1.DataValueField = "Id";
ddllocation1.DataBind();
ddllocation1.Items.Insert(0, new ListItem("--Select--", "0"));
ddllocation1.Items.Insert(1, new ListItem("--OTHER--", "0"));
con.Close();
}
}
protected void ddllocation1_SelectedIndexChanged(object sender, EventArgs e)
{
string country = "India";
var cities = _helper.GetLocations(country, ddllocation1.SelectedValue);
cities.Insert(0, "--Select--");
cities.Insert(1, "Other");
ddlLocation.DataSource = cities;
ddlLocation.DataBind();
}
protected void btnAddDropDown_Click1(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
//BindContrydropdown();
//if (txtOtherCity.Text != "")
//{
// txtOtherCity.Text = "";
//}
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Add_CityforLocation";
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = 0;
cmd.Parameters.Add("#CountryName", SqlDbType.VarChar).Value = "India";
cmd.Parameters.Add("#CityName", SqlDbType.VarChar).Value = txtOtherCity.Text.Trim();
cmd.Parameters.Add("#StateName", SqlDbType.VarChar).Value = ddlLocation.SelectedItem.ToString();
cmd.Connection = con;
try
{
// con.Open();
cmd.ExecuteNonQuery();
BindContrydropdown();
// lblMessage.Text = "City inserted successfully!";
}
catch (Exception ex)
{
Response.Write(ex.Message);//You Can Haave Messagebox here
}
finally
{
con.Close();
}
}
}
Also see the html of the dropdowns:-
<tr>
<td class="td">Location/State</td>
<td>
<asp:DropDownList CssClass="txtfld-popup" ID="ddllocation1" OnSelectedIndexChanged="ddllocation1_SelectedIndexChanged" runat="server" AutoPostBack="true"></asp:DropDownList>
<asp:RequiredFieldValidator CssClass="error_msg" ID="RequiredFieldValidator1" ControlToValidate="ddllocation1" runat="server" ErrorMessage="Please enter location" InitialValue="--Select--" SetFocusOnError="true"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="td">Location/City</td>
<td>
<asp:DropDownList CssClass="txtfld-popup" ID="ddlLocation" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlLocation_SelectedIndexChanged"></asp:DropDownList>
<asp:RequiredFieldValidator CssClass="error_msg" ID="reqLocation" ControlToValidate="ddlLocation" runat="server" ErrorMessage="Please enter location" InitialValue="--Select--" SetFocusOnError="true"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtOtherCity" runat="server" Visible="false" CssClass="txtfld-popup"></asp:TextBox>
<asp:Button ID="btnAddDropDown" runat="server" Width="63" Text="Add" CausesValidation="false" OnClick="btnAddDropDown_Click1" />
</td>
</tr>
And this solved my,
Also see the Stored procedure for the same:-
Alter PROCEDURE [dbo].[Add_CityforLocation]
-- Add the parameters for the stored procedure here
#ID int,
#CountryName nvarchar(100),
#StateName nvarchar(100),
#CityName varchar(100)
AS
BEGIN
INSERT INTO Career.Location(CountryName, StateName, CityName) values (#CountryName,#StateName,#CityName)
END
GO
i am trying to get data from the stored procedure into the dropdownlist when the event onSelectIndexChanged is fired. But after putting the break point i get to know that the event generated is not working i.e. the control doesnot even goes into that code.
<tr>
<td><asp:Label ID="Label5" runat="server" Text="Book Category"></asp:Label></td>
<td>
<asp:DropDownList ID="ddlBookCategory" runat="server" Height="20px" Width="250px" OnSelectedIndexChanged="ddlBookCategory_SelectedIndexChanged" >
</asp:DropDownList>
</td>
</tr>
<tr>
<td><asp:Label ID="Label4" runat="server" Text="Book Subject"></asp:Label></td>
<td>
<asp:DropDownList ID="ddlBookSubject" runat="server" Height="20px" Width="250px" >
</asp:DropDownList>
</td>
</tr>
and the backend cs file coding is::
protected void Page_Load(object sender, EventArgs e)
{
connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ToString();
lblmsg.Visible = false;
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
try
{
con.Open();
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "ShowBookCategory";
cmd.Connection = con;
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
ddlBookCategory.Items.Add(new ListItem(reader["CategoryName"].ToString()));
}
}
}
catch (OleDbException ex)
{
ex.Data.ToString();
}
}
protected void ddlBookCategory_SelectedIndexChanged(object sender, EventArgs e)
{
ddlBookCategory.AutoPostBack = true;
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd2 = new OleDbCommand();
MbERPLibraryBookSubjectProperty foc = new MbERPLibraryBookSubjectProperty();
try
{
con.Open();
cmd2.CommandType = System.Data.CommandType.StoredProcedure;
cmd2.CommandText = "ShowBookSubjectWithCategory";
cmd2.Connection = con;
foc.CategoryName = ddlBookCategory.Text.ToString();
cmd2.Parameters.Add(new OleDbParameter("#CategoryName", foc.CategoryName));
cmd2.Parameters["#CategoryName"].Direction = System.Data.ParameterDirection.Input;
OleDbDataReader reader2 = cmd2.ExecuteReader();
if (reader2.HasRows)
{
while (reader2.Read())
{
ddlBookSubject.Items.Add(new ListItem(reader2["SubjectName"].ToString()));
}
}
}
catch (OleDbException ex)
{
ex.Data.ToString();
}
}
And my stored Procedure is:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Procedure [dbo].[ShowBookSubjectWithCategory](
#CategoryName varchar(50)
)
AS
BEGIN
select * from BookSubjects Where CategoryName = #CategoryName
END
Instead of declaring autoPostBack as true in your event handler, try to set it in DropDownList declaration like bellow:
<asp:DropDownList ID="ddlBookCategory" ... autopostback="true" ... >
...
</asp:DropDownList>
If you want to set ddlBookCategory.AutoPostBack = true; dynamically then set that in pageload event.
You need to add AutoPostBack =true to the control in order for the control to signal back to the server that an event has occurred. Once you do that you can set an event handler to a method in your code behind for the selected index changed event on that control.