Issue With Session pass in another page in asp.net? - c#

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

Related

Asp:Label that determined by dropdownlistbox not working properly

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();

Can't JOIN tables in ASP.NET

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.

How to update Value from the textbox user puts in

I have a code like this
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Visible="False" Text="Please update the price"></asp:Label>
<br />
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
and C# is
namespace WebApplication6
{
public partial class WebForm20 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["onealbumid"] != null)
{
Label1.Visible = true;
int onealbumid = Convert.ToInt32(Session["onealbumid"]);
String Artists = System.Configuration.ConfigurationManager.ConnectionStrings["FleetManagementConnectionString"].ConnectionString;
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(Artists);
SqlCommand cmd = new SqlCommand("Select Price from OneAlbum where OneALbumID='" + onealbumid + "'", con);
con.Open();
TextBox1.Text = cmd.ExecuteScalar().ToString();
con.Close();
}
else {
Response.Redirect("~/BENEinsertOneAlbum3.aspx");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
String Artists = System.Configuration.ConfigurationManager.ConnectionStrings["FleetManagementConnectionString"].ConnectionString;
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(Artists);
int onealbumid = Convert.ToInt32(Session["onealbumid"]);
SqlCommand command = new SqlCommand(#"UPDATE [dbo].[OneAlbum]
SET Price=#Price where OneAlbumID =" + onealbumid + ";", con);
command.Parameters.AddWithValue("#Price", TextBox1.Text);
con.Open();
command.ExecuteNonQuery();
con.Close();
Response.Redirect("~/BENEinsertOneAlbum3.aspx");
}
}
}
There is a page/form, before this page, users select the price which users want to change from the gridview
I want users to edit new "Price" in the textbox1 on this page.
So this is happening right now.
For example, I choose "Price" 22 before this page and when this page opens/loads textbox1 showing 22.
so I change/type to 40 in Texbox1, and click button.
The price is still 22. not 40 and I checked the database, which still did not change, still 22
why is this happening?
The Page_Load will overwrite the data you are entering. Put a !IsPostBack check around that so that when you do click the button the data isn't being put back to what it was when the form loaded.
Also, where is a gridview in this code? There is such a class and thus beware of what terms you use given the code you show.

Dropdown value disappears after submit

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

OnSelectedIndexChanged event not working

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.

Categories