I have a method that i would like to use multiple times, that basically populates a Dropdown List.
public void PopulateDropdown(string selectedValue, object listname)
{
String connString = ConfigurationManager.ConnectionStrings["MySql"].ToString(); //Conn string
MySqlConnection mySqlConnection = new MySqlConnection(connString); //Objekt
MySqlCommand cmd = new MySqlCommand(); //cmd objekt
cmd.CommandText = "SELECT NAME FROM CustomerDb WHERE CITY = \"" + selectedValue + "\"";
cmd.CommandType = CommandType.Text;
cmd.Connection = mySqlConnection;
DropDownList dropDownList = listname as DropDownList;
mySqlConnection.Open();
dropDownList.DataSource = cmd.ExecuteReader();
dropDownList.DataTextField = "NAME";
dropDownList.DataBind();
mySqlConnection.Close();
}
My call looks like this:
protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
{
string value = DropDownList3.SelectedValue;
PopulateDropdown(value, DropDownList4);
}
I know that my call and my method is correct, but for some reason, im not able to call it in DropDownList3_SelectedIndexChanged.
When i select a value in DropDownList3 it just reloads and picks the default value "Select city".
<asp:DropDownList ID="DropDownList3" CssClass="btn btn-default btn-md pull-right" runat="server" OnSelectedIndexChanged="DropDownList3_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem>Select city</asp:ListItem>
<asp:ListItem>City1</asp:ListItem>
<asp:ListItem>City2</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList4" runat="server" CssClass="btn btn-default btn-md pull-right" OnSelectedIndexChanged="DropDownList4_SelectedIndexChanged" AutoPostBack="true" Style="">
</asp:DropDownList>
my DropDownList3_SelectedIndexChanged looks like this:
protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
{
string value = DropDownList3.SelectedValue;
PopulateDropdown(value, DropDownList4);
}
The postback doesn't reach breakpoint in method.
Well I don't really know if this will answer your question, but when getting a value from the database and using those data to fill a combobox or dropdownlist, I use this code/query:
String path = "Data Source = LOCALHOST; Initial Catalog= sample_database; username='root'; password=''";
MySqlConnection sqlcon = new MySqlConnection(path);
MySqlCommand sqlcom = new MySqlCommand();
MySqlDataReader sqlread;
sqlcon.Open();
sqlcom.CommandType = CommandType.Text;
sqlcom.CommandText = "SELECT name from database_table where city = '"+TextBox1.text+"'";
sqlcom.Connection = sqlcon;
sqlread = sqlcom.ExecuteReader();
while (sqlread.Read()) //use loop to get all data in the specified column
comboBox1.Items.Add(sqlread[0].ToString()); //place the data gathered in the combobox or dropdownlist
sqlcon.Close();
It could be that you're populating the City list on page load, and the AutoPostBack reloads the list. See DropDownList's SelectedIndexChanged event not firing
Related
I want to create 3 Dropdown List for (Country, City and State) Cascading on Selection for The First Dropdown list Changing The Second and Selection for the second Changing The Third with SQL Server (ADO.Net) and ASP.Net C#!
and this error showing me
Can any one solve this error Please ?
Here the asp.net design code The Fist one..enter image description here
<asp:DropDownList ID="ddlFirst" runat="server" AutoPostBack="True" AppendDataBoundItems="True"
onselectedindexchanged="ddlFirst_SelectedIndexChanged">
<asp:ListItem Value="0">--Select Location--</asp:ListItem>
</asp:DropDownList>
The Second one:
<asp:DropDownList ID="ddlSecond" runat="server" AppendDataBoundItems="true" DataTextField="City"
DataValueField="City" AutoPostBack="True"
onselectedindexchanged="ddlSecond_SelectedIndexChanged">
<asp:ListItem Value="0">-- Select City--</asp:ListItem>
</asp:DropDownList>
And The Third..
<asp:DropDownList ID="ddlThird" runat="server" AppendDataBoundItems="true" DataTextField="State"
DataValueField="State">
<asp:ListItem Value="0">-- Select Area--</asp:ListItem>
</asp:DropDownList>
, the code of page load..enter image description here
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
try
{
txtid.Text = (pr.Project.OrderByDescending(b => b.ProID).FirstOrDefault().ProID
+1).ToString();
}
catch
{
txtid.Text = "1";
}
btnadd.Visible = true;
btndelete.Visible = false;
btnupdate.Visible = false;
GridView1.DataSource = pr.Project.ToList();
GridView1.DataBind();
}
if (!Page.IsPostBack)
{
SqlConnection con = new SqlConnection(#"Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\GROUP.mdf;Integrated Security=True;User
Instance=True");
SqlCommand cmd = new SqlCommand("select * from Project", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
ddlFirst.DataSource = dt;
ddlFirst.DataBind();
}
}
, code of dropdown lists with c#..enter image description here
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
ddlSecond.Items.Clear();
ddlSecond.Items.Add("Select State");
SqlConnection con = new SqlConnection(#"Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\GROUP.mdf;Integrated Security=True;User
Instance=True");
SqlCommand cmd = new SqlCommand("select [City] from Project where Location=" +
ddlFirst.SelectedItem.Value, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
ddlSecond.DataSource = dt;
ddlSecond.DataBind();
}
protected void ddlSecond_SelectedIndexChanged(object sender, EventArgs e)
{
ddlSecond.Items.Clear();
ddlSecond.Items.Add("Select State");
SqlConnection con = new SqlConnection(#"Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\GROUP.mdf;Integrated Security=True;User
Instance=True");
SqlCommand cmd = new SqlCommand("select [State] from Project where City=" +
ddlSecond.SelectedItem.Value, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
ddlSecond.DataSource = dt;
ddlSecond.DataBind();
}
and < The Error >..enter image description here
Server Error in '/' Application.
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request.
Please review the following specific error details and modify your source code appropriately.
Compiler Error Message:
CS1061: 'ASP.webusercontrol_project_wuc_ascx' does not contain a definition for 'ddlFirst_SelectedIndexChanged' and no extension method 'ddlFirst_SelectedIndexChanged' accepting a first argument of type 'ASP.webusercontrol_project_wuc_ascx' could be found (are you missing a using directive or an assembly reference?)
Source Error:
Line 94:
Line 95:
Line 96: <asp:DropDownList ID="ddlFirst" runat="server" AutoPostBack="True" AppendDataBoundItems="True"
Line 97: onselectedindexchanged="ddlFirst_SelectedIndexChanged">
Line 98: <asp:ListItem Value="0">--Select Location--</asp:ListItem>
Source File: g:\Projects\Admin-WebApp-Final-Version\WebUserControl\Project-WUC.ascx Line: 96
I tried to create it with javascript only and it didn't work, and I tried to create it without a database and it didn't work
The error message...
CS1061: 'ASP.webusercontrol_project_wuc_ascx' does not contain a definition for 'ddlFirst_SelectedIndexChanged' and no extension method 'ddlFirst_SelectedIndexChanged' accepting a first argument of type 'ASP.webusercontrol_project_wuc_ascx' could be found (are you missing a using directive or an assembly reference?)
... is a slightly long-winded way of telling you that you're trying to call a method called ddlFirst_SelectedIndexChanged but the compiler couldn't find a method which meets that description.
From the name of the method that the compiler is looking for, I guess it's probably intended to be an event handler for the user changing the selection in the first drop-down list, so let's check that...
<asp:DropDownList ID="ddlFirst" runat="server" AutoPostBack="True" AppendDataBoundItems="True"
onselectedindexchanged="ddlFirst_SelectedIndexChanged">
<asp:ListItem Value="0">--Select Location--</asp:ListItem>
</asp:DropDownList>
Yep, this is what is causing the compiler to look for a method with that name, so let's see what the event handler method is actually called.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
And there's the answer - the event handler is called DropDownList1_SelectedIndexChanged, not ddlFirst_SelectedIndexChanged. Renaming the method to ddlFirst_SelectedIndexChanged should make the compiler error go away.
As an aside, concatenating user input into a SQL statement like this...
SqlCommand cmd = new SqlCommand("select [City] from Project where Location=" +
ddlFirst.SelectedItem.Value, con);
... isn't a great idea, because it's vulnerable to SQL injection attacks, which a malicious user could use to do serious damage to your database. Using stored procedures, or an object relational mapper such as Entity Framework, is a much safer way of implementing your data access.
If you use parameter's, you find this code quite a bit easier.
Say this markup:
<div style="float:left">
<h4>Region</h4>
<asp:DropDownList ID="cboRegion" runat="server"
DataTextField="Region"
AutoPostBack="true"
OnSelectedIndexChanged="cboRegion_SelectedIndexChanged" >
</asp:DropDownList>
</div>
<div style="float:left;margin-left:25px">
<h4>Country</h4>
<asp:DropDownList ID="cboCountry" runat="server" Width="250px"
DataTextField="Country"
AutoPostBack="true"
OnSelectedIndexChanged="cboCountry_SelectedIndexChanged" >
</asp:DropDownList>
</div>
<div style="float:left;margin-left:25px">
<h4>State</h4>
<asp:DropDownList ID="cboState" runat="server" Width="200px"
DataTextField="state"
AutoPostBack="true"
OnSelectedIndexChanged="cboState_SelectedIndexChanged" >
</asp:DropDownList>
</div>
<div style="float:left;margin-left:25px">
<h4>City</h4>
<asp:DropDownList ID="cboCity" runat="server" Width="220"
DataTextField="city"
dataValueField="ID"
AutoPostBack="true"
OnSelectedIndexChanged="cboCity_SelectedIndexChanged" >
</asp:DropDownList>
</div>
Note how I "avoided" using the item list in the drop down boxes. The reason is if you re-fill, then you will have difficulty in clearing out the drop boxes.
And now our code is this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
// load up first cbo box, region
SqlCommand cmdSQL =
new SqlCommand("SELECT region from vRegion ORDER BY region");
cboRegion.DataSource = MyRstP(cmdSQL);
cboRegion.DataBind();
cboRegion.Items.Insert(0, new ListItem("Select Region", ""));
}
protected void cboRegion_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboRegion.SelectedIndex > 0)
{
string strSQL =
#"SELECT Country FROM vCountryRegion
WHERE region = #region
ORDER BY Country";
SqlCommand cmdSQL = new SqlCommand(strSQL);
cmdSQL.Parameters.Add("#region", SqlDbType.NVarChar).Value = cboRegion.Text;
cboCountry.DataSource = MyRstP(cmdSQL);
cboCountry.DataBind();
cboCountry.Items.Insert(0, new ListItem("Select Country", ""));
}
}
protected void cboCountry_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboCountry.SelectedIndex > 0)
{
string strSQL =
#"SELECT state from vCountryStates
WHERE Country = #Country
ORDER BY state";
SqlCommand cmdSQL = new SqlCommand(strSQL);
cmdSQL.Parameters.Add("#Country", SqlDbType.NVarChar).Value = cboCountry.Text;
cboState.DataSource = MyRstP(cmdSQL);
cboState.DataBind();
cboState.Items.Insert(0, new ListItem("Select State", ""));
}
}
protected void cboState_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboState.SelectedIndex > 0)
{
string strSQL =
#"SELECT id, city from vCities
WHERE Country_name = #Country
AND state_name = #State
ORDER BY city";
SqlCommand cmdSQL = new SqlCommand(strSQL);
cmdSQL.Parameters.Add("#Country", SqlDbType.NVarChar).Value = cboCountry.Text;
cmdSQL.Parameters.Add("#State", SqlDbType.NVarChar).Value = cboState.Text;
cboCity.DataSource = MyRstP(cmdSQL);
cboCity.DataBind();
cboCity.Items.Insert(0, new ListItem("Select City", ""));
}
}
And the result is now this:
And in the above, I also had this little routine (no need to type over and over the code to build a connection and load the data).
DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.Countries))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
I have this asp:gridview in which I show data using mySql stored procedure. I have this listbox named ddlstatus which I use to filter the data. I use viewstate to show data that are selected from the listbox. The problem is I want to make multiple selection on this listbox and show data for each selection made on it, but when it only shows data for the initial selection.
The below is the client side code:
<asp:Label ID="lblstat" Text="status" Visible="false" runat="server"></asp:Label>
<asp:ListBox ID="ddlstatus" runat="server" OnSelectedIndexChanged="DropDownChange" AutoPostBack="true" AppendDataBoundItems="true" SelectionMode="Multiple"></asp:ListBox>
<asp:GridView ID="gdvTM" runat="server" ControlStyle-Width="100%" AutoGenerateColumns="False" DataKeyNames="ID" OnRowDeleting="gdvTM_RowDeleting" PageSize="5" CssClass="cssgridview" AlternatingRowStyle-BackColor="#d5d8dc">
<Columns >
<asp:TemplateField HeaderText="Current Status">
<ItemTemplate >
<asp:Label ID="lblcstat" runat="server" Text='<%# Eval("status") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The below is the server side code:
private void BindDropDownList()
{
PopulateDropDown(ddlstatus, lblstat.Text);
}
private void PopulateDropDown(ListBox ddl, string columnName)
{
ddl.Items.Clear();
ddl.DataSource = BindDropDown(columnName);
ddl.DataTextField = columnName;
ddl.DataValueField = columnName;
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("Please select", "0"));
}
private void BindGrid()
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlDataAdapter sda = new MySqlDataAdapter();
MySqlCommand cmd = new MySqlCommand("GetTMData");
cmd.CommandType = CommandType.StoredProcedure;
string statusVal = null;
if (ViewState["stat"] != null && ViewState["stat"].ToString() != "0")
{
statusVal = ViewState["stat"].ToString();
}
cmd.Parameters.AddWithValue("statusVal", statusVal);
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
gdvTM.DataSource = dt;
int i = dt.Rows.Count;
gdvTM.DataBind();
this.BindDropDownList();
TableCell cell = gdvTM.HeaderRow.Cells[0];
setDropdownselectedItem(ViewState["stat"] != null ? (string)ViewState["stat"] : string.Empty, ddlstatus);
}
private void setDropdownselectedItem(string selectedvalue, ListBox ddl)
{
if (!string.IsNullOrEmpty(selectedvalue))
{
ddl.Items.FindByValue(selectedvalue).Selected = true;
}
}
protected void DropDownChange(object sender, EventArgs e)
{
ListBox dropdown = (ListBox)sender;
string selectedValue = dropdown.SelectedItem.Value;
switch (dropdown.ID.ToLower())
{
case "ddlstatus":
ViewState["stat"] = selectedValue;
break;
}
this.BindGrid();
}
private DataTable BindDropDown(string columnName)
{
string username = uName.Text;
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlCommand cmd = new MySqlCommand("SELECT DISTINCT (" + columnName + ") FROM approved WHERE tm = #tm AND " + columnName + " IS NOT NULL", con);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
cmd.Parameters.AddWithValue("#tm", username);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
Below is the MySql stored procedure:
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetTMData`(in statusVal varchar(45))
BEGIN
SELECT *
FROM approved
WHERE (statusVal IS NULL
OR status = statusVal)
order by date desc;
END
How can I make this happen? Thanks in advance.
Please make listbox multiple
<asp:ListBox id="ListBox1"
Rows="6"
Width="100px"
**SelectionMode="Multiple"**
runat="server">
<asp:ListItem Selected="True">Item 1</asp:ListItem>
<asp:ListItem>Item 2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
<asp:ListItem>Item 4</asp:ListItem>
<asp:ListItem>Item 5</asp:ListItem>
<asp:ListItem>Item 6</asp:ListItem>
</asp:ListBox>
Then in server side
void SubmitBtn_Click(Object sender, EventArgs e)
{
Message.Text = "You chose: <br />";
// Iterate through the Items collection of the ListBox and
// display the selected items.
foreach (ListItem item in ListBox1.Items)
{
if(item.Selected)
{
Message.Text += item.Text + "<br />";
}
}
}
First of all, auto post back not allow you to select multiple items because upto select second item, the postback already happens by first selected item so,
You have to set AutoPostBack="false" for your list box,
<asp:ListBox ID="ddlstatus" runat="server" AutoPostBack="false" AppendDataBoundItems="true" SelectionMode="Multiple"></asp:ListBox>
For collecting multiple selected items we simply choose button for instance, you can collect those items wherever you want,
Then add one button that will call below code
<asp:Button ID="button1" runat="server" OnClick="button1_Click" Text="Click"/>
On above button event handler add below code,
protected void button1_Click(object sender, EventArgs e)
{
var selectedNames = ddlstatus.Items.Cast<ListItem>()
.Where(i => i.Selected)
.Select(i => i.Value)
.ToList();
string selectedValue = string.Join("','", selectedNames);
selectedValue = "'" + selectedValue + "'";
ViewState["stat"] = selectedValue;
}
Then the comma separated items in your ViewState will be used in your stored procedure parameter
string statusVal = null;
if (ViewState["stat"] != null && ViewState["stat"].ToString() != "0")
{
statusVal = ViewState["stat"].ToString();
}
cmd.Parameters.AddWithValue("statusVal", statusVal); //<= Now this string variable contains comma separated list box items values.
If you populate your list box on Page_Load then make sure that you should populate it into !Page.IsPostBack like
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Populate your list box here
}
}
And your SP is
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetTMData1`(in statusVal varchar(255))
BEGIN
IF statusVal = '\'\'' THEN
select * from approved;
ELSE
SET #sql = CONCAT('SELECT * FROM approved WHERE status IN (', statusVal, ')');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF ;
END
If you select multiple items from the dropdown then your SP's parameter data look like '\'apple\',\'banana\''. If not then it look like '\''.
There's a few issues that I could spot that may need to be addressed,
Ensure that the method BindDropDownList is only called on a non postback (page refresh), because your method PopulateDropDown is clearing the items on the list which means that viewstate cannot be restored in a postback, hence the probable reason why only one item is being selected.
I'm not 100% of the table schema, but the SQL provided does not seem to be able to query by more than one status properly, you should probably send a comma separated list of values, and in SQL turn them into a temp table so that you effectively search for items with multiple status (you should probably create a new question for this).
Do not use SelectedItem for multiple selections, instead you need to iterate your list items for those that are selected, and you don't need to use ViewState to pass it along (you probably did because of point 1. above). For example you could replace your method BindGrid and DropDownChange with:
private void BindGrid()
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlDataAdapter sda = new MySqlDataAdapter();
MySqlCommand cmd = new MySqlCommand("GetTMData");
cmd.CommandType = CommandType.StoredProcedure;
string statusVal = null;
foreach (ListItem item in ddlstatus.Items)
{
if(item.Selected)
{
if(statusVal.length > 0)
statusVal += ",";
statusVal += item.Value;
}
}
cmd.Parameters.AddWithValue("statusVal", statusVal);
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
gdvTM.DataSource = dt;
gdvTM.DataBind();
}
protected void DropDownChange(object sender, EventArgs e)
{
this.BindGrid();
}
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 made search box using textbox and button control to search the data in my GridView, for datasource I'm using ObjectDataSource. In ObjectDataSource Class I'm Using parameterized procedure to select data from database table, but the problem was occured here, ObjectDataSource expect a value for parameter class. I have solved this with hardcoded the class if it null give the parameter value equals to white space, it works good.
If there is another way solve this without hardcoded the class, any answers would be helpful, thanks
Here is my ObjectDataSource Select Class
public static List<T_Penerbit> GetSearchPenerbit(string Cari)
{
if (string.IsNullOrWhiteSpace(Cari))
{
Cari = " ";
}
List<T_Penerbit> listSearchPenerbit = new List<T_Penerbit>();
string cs = ConfigurationManager.ConnectionStrings["cs_perpustakaan"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetPenerbitBySearch", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramSearch = new SqlParameter("#parameter", Cari);
cmd.Parameters.Add(paramSearch);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
T_Penerbit penerbit = new T_Penerbit();
penerbit.ID = Convert.ToInt32(rdr["ID"]);
penerbit.Penerbit = rdr["Nama_Penerbit"].ToString();
penerbit.Kota = rdr["Kota"].ToString();
penerbit.Handphone = rdr["Handphone"].ToString();
penerbit.Email = rdr["Email"].ToString();
listSearchPenerbit.Add(penerbit);
}
}
return listSearchPenerbit;
}
And here is my button Search Click event
protected void ButtonKelolaDataPenerbitCariPenerbit_Click(object sender, EventArgs e)
{
ObjectDataSourceCariDataPenerbit.SelectParameters.Clear();
ObjectDataSourceCariDataPenerbit.SelectParameters.Add("Cari", TextBoxKelolaDataPenerbitCariPenerbit.Text);
ObjectDataSourceCariDataPenerbit.DataBind();
}
Presentation changes :
<div style="margin-top:50px">
SEARCHING
<br /><br />
Enter Id : -
<asp:TextBox ID="txtSearchId" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />
</div>
Back-end updates :
protected void btnSearch_Click(object sender, EventArgs e)
{
SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["StudDBConnectionString"].ToString());
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = "select * from tbl_stud where id="+txtSearchId.Text;
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);
grvStudentWithoutDatasource.DataSource = dataTable;
grvStudentWithoutDatasource.DataBind();
}
Note: The given code is according to my database, Please change database column accordingly.
try this
aspx file:
<asp:ObjectDataSource runat="server" ID=" ObjectDataSourceCariDataPenerbit" TypeName="Penerbit" SelectMethod="GetSearchPenerbit">
<SelectParameters>
<asp:ControlParameter ControlID="TextBoxKelolaDataPenerbitCariPenerbit" Name="Cari" Type="String" />
</SelectParameters>
</asp:ObjectDataSource>
button Search Click event
protected void ButtonKelolaDataPenerbitCariPenerbit_Click(object sender, EventArgs e)
{
ObjectDataSourceCariDataPenerbit.DataBind();
}
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