Update Panels with drop down lists asp.net/c# - c#

I am trying to user the select from one drop down list to filter another one, with update panels so it doesn't refresh the page. However, I cannot get it to work.
Here is the code below:
ASPX (This is below all JS content):
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
Module Code*
<asp:DropDownList ID="ModuleCodeDDL" AutoPostBack="true" OnSelectedIndexChanged="ModuleCodeDDL_SelectedIndexChanged" Style="width: 200px;" runat="server"></asp:DropDownList>
Module Name*
<asp:DropDownList ID="ModuleTitleDDL" AutoPostBack="true" Style="width: 250px;" runat="server"></asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
THE CODE BEHIND (C#):
//I INITIALLY POPULATE THE TWO DROP DOWN LISTS
connect.Open();
string moduleSql = "Select Module_Code, Module_Title from [newModule]";
SqlCommand moduleCommand = new SqlCommand(moduleSql, connect);
SqlDataReader modules = moduleCommand.ExecuteReader();
while (modules.Read())
{
string moduleCode = modules.GetString(0);
string moduleName = modules.GetString(1);
string module = moduleCode;
ModuleCodeDDL.Items.Add(module);
}
connect.Close();
connect.Open();
string moduleSql1 = "Select Module_Code, Module_Title from [newModule]";
SqlCommand moduleCommand1 = new SqlCommand(moduleSql1, connect);
SqlDataReader modules1 = moduleCommand1.ExecuteReader();
while (modules1.Read())
{
string moduleCode = modules1.GetString(0);
string moduleName = modules1.GetString(1);
string module = moduleName;
ModuleTitleDDL.Items.Add(module);
}
connect.Close();
}
//THIS IS THE FUNCTION THAT IS CALLED WITH THE ONSELECTEDINDEXCHANGED
protected void ModuleCodeDDL_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection connect = new SqlConnection(WebConfigurationManager.ConnectionStrings["ParkConnectionString"].ToString());
ModuleTitleDDL.Items.Clear();
connect.Open();
string moduleCode = ModuleCodeDDL.SelectedItem.Value;
string moduleTitleSQL = "Select Module_Code, Module_Title From [newModule] Where Module_Code ='" + moduleCode + "'";
SqlCommand moduleTitleNew = new SqlCommand(moduleTitleSQL, connect);
SqlDataReader newModuleTitle1 = moduleTitleNew.ExecuteReader();
ModuleTitleDDL.Items.Add("");
while (newModuleTitle1.Read())//Add the results to the dropdownlist
{
ModuleTitleDDL.Items.Add(newModuleTitle1.GetString(1).ToString());
}
connect.Close();
}
It works without Update Panels with a full post back, but I can't seem to get it to work with Update Panels.
If anyone could shed some light on how to fix this issue, it would be much appreciated.
Thanks in advance!

Related

Object accepting method doesn't populate dropdown

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

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.

ASP.NET AJAX Toolkit keeps adding the new content into the old one

I have this ASP.NET AJAX toolkit. Each time AJAX is triggered, I get the old data + new data , and it keeps adding and adding ( because I have the += in the code behind) How can I solve this, so that AJAX only shows the updated version, and not keeps adding?
aspx:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="1000"></asp:Timer>
<ul id="myaspajaxtoolkit" runat="server"></ul>
</ContentTemplate>
</asp:UpdatePanel>
code behind:
SqlConnection cnn = new SqlConnection("Initial Catalog=Northwind;Data Source=localhost;Integrated Security=SSPI;");
protected void Page_Load(object sender, EventArgs e)
{
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT EmployeeName FROM Employees", cnn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
myaspajaxtoolkit.InnerHtml += "<li>" + dr.GetString(0) + "</li>";
}
}
cnn.Close();
}
string html = string.Empty;
if (dr.HasRows)
{
while (dr.Read())
{
html+= "<li>" + dr.GetString(0) + "</li>";
}
}
myaspajaxtoolkit.InnerHtml = html;

What is the right way to populate a DropDownList from a database?

I am populating a DropDownList from a SQL Server database as shown below. It works fine, but I'm not sure it's a good way. Can someone shed some light on this method, and give some improvements?
private void LoadSubjects()
{
ddlSubjects.Items.Clear();
string selectSQL = "SELECT SubjectID,SubjectName FROM Students.dbo.Subjects";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
ListItem newItem = new ListItem();
newItem.Text = "<Select Subject>";
newItem.Value = "0";
ddlSubjects.Items.Add(newItem);
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
newItem = new ListItem();
newItem.Text = reader["SubjectName"].ToString();
newItem.Value = reader["SubjectID"].ToString();
ddlSubjects.Items.Add(newItem);
}
reader.Close();
}
catch (Exception err)
{
//TODO
}
finally
{
con.Close();
}
}
You could bind the DropDownList to a data source (DataTable, List, DataSet, SqlDataSource, etc).
For example, if you wanted to use a DataTable:
ddlSubject.DataSource = subjectsTable;
ddlSubject.DataTextField = "SubjectNamne";
ddlSubject.DataValueField = "SubjectID";
ddlSubject.DataBind();
EDIT - More complete example
private void LoadSubjects()
{
DataTable subjects = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT SubjectID, SubjectName FROM Students.dbo.Subjects", con);
adapter.Fill(subjects);
ddlSubject.DataSource = subjects;
ddlSubject.DataTextField = "SubjectNamne";
ddlSubject.DataValueField = "SubjectID";
ddlSubject.DataBind();
}
catch (Exception ex)
{
// Handle the error
}
}
// Add the initial item - you can add this even if the options from the
// db were not successfully loaded
ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));
}
To set an initial value via the markup, rather than code-behind, specify the option(s) and set the AppendDataBoundItems attribute to true:
<asp:DropDownList ID="ddlSubject" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="<Select Subject>" Value="0" />
</asp:DropDownList>
You could then bind the DropDownList to a DataSource in the code-behind (just remember to remove:
ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));
from the code-behind, or you'll have two "" items.
I hope I am not overstating the obvious, but why not do it directly in the ASP side? Unless you are dynamically altering the SQL based on certain conditions in your program, you should avoid codebehind as much as possible.
You could do the above all in ASP directly without code using the SqlDataSource control and a property in your dropdownlist.
<asp:GridView ID="gvSubjects" runat="server" DataKeyNames="SubjectID" OnRowDataBound="GridView_RowDataBound" OnDataBound="GridView_DataBound">
<Columns>
<asp:TemplateField HeaderText="Subjects">
<ItemTemplate>
<asp:DropDownList ID="ddlSubjects" runat="server" DataSourceID="sdsSubjects" DataTextField="SubjectName" DataValueField="SubjectID">
</asp:DropDownList>
<asp:SqlDataSource ID="sdsSubjects" runat="server"
SelectCommand="SELECT SubjectID,SubjectName FROM Students.dbo.Subjects"></asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
public void getClientNameDropDowndata()
{
getConnection = Connection.SetConnection(); // to connect with data base Configure manager
string ClientName = "Select ClientName from Client ";
SqlCommand ClientNameCommand = new SqlCommand(ClientName, getConnection);
ClientNameCommand.CommandType = CommandType.Text;
SqlDataReader ClientNameData;
ClientNameData = ClientNameCommand.ExecuteReader();
if (ClientNameData.HasRows)
{
DropDownList_ClientName.DataSource = ClientNameData;
DropDownList_ClientName.DataValueField = "ClientName";
DropDownList_ClientName.DataTextField="ClientName";
DropDownList_ClientName.DataBind();
}
else
{
MessageBox.Show("No is found");
CloseConnection = new Connection();
CloseConnection.closeConnection(); // close the connection
}
}
((TextBox)GridView1.Rows[e.NewEditIndex].Cells[3].Controls[0]).Enabled = false;

How to make an autocomplete TextBox in ASP.NET?

How do I make an autocomplete TextBox in C# that binds to a data source?
You can use either jQuery Autocomplete or ASP.NET AJAX Toolkit Autocomplete
I use ajaxcontrol toolkit's AutoComplete
Try this:
.aspx page
<td>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"OnTextChanged="TextBox1_TextChanged"></asp:TextBox>
<asp:AutoCompleteExtender ServiceMethod="GetCompletionList" MinimumPrefixLength="1"
CompletionInterval="10" EnableCaching="false" CompletionSetCount="1" TargetControlID="TextBox1"
ID="AutoCompleteExtender1" runat="server" FirstRowSelected="false">
</asp:AutoCompleteExtender>
Now To auto populate from database :
public static List<string> GetCompletionList(string prefixText, int count)
{
return AutoFillProducts(prefixText);
}
private static List<string> AutoFillProducts(string prefixText)
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
using (SqlCommand com = new SqlCommand())
{
com.CommandText = "select ProductName from ProdcutMaster where " + "ProductName like #Search + '%'";
com.Parameters.AddWithValue("#Search", prefixText);
com.Connection = con;
con.Open();
List<string> countryNames = new List<string>();
using (SqlDataReader sdr = com.ExecuteReader())
{
while (sdr.Read())
{
countryNames.Add(sdr["ProductName"].ToString());
}
}
con.Close();
return countryNames;
}
}
}
Now:create a stored Procedure that fetches the Product details depending on the selected product from the Auto Complete Text Box.
Create Procedure GetProductDet
(
#ProductName varchar(50)
)
as
begin
Select BrandName,warranty,Price from ProdcutMaster where ProductName=#ProductName
End
Create a function name to get product details ::
private void GetProductMasterDet(string ProductName)
{
connection();
com = new SqlCommand("GetProductDet", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#ProductName", ProductName);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds=new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
con.Close();
//Binding TextBox From dataTable
txtbrandName.Text =dt.Rows[0]["BrandName"].ToString();
txtwarranty.Text = dt.Rows[0]["warranty"].ToString();
txtPrice.Text = dt.Rows[0]["Price"].ToString();
}
Auto post back should be true
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>
Now, Just call this function
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
//calling method and Passing Values
GetProductMasterDet(TextBox1.Text);
}
1-Install AjaxControl Toolkit easily by Nugget
PM> Install-Package AjaxControlToolkit
2-then in markup
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:TextBox ID="txtMovie" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" TargetControlID="txtMovie"
runat="server" />
3- in code-behind : to get the suggestions
[System.Web.Services.WebMethodAttribute(),System.Web.Script.Services.ScriptMethodAttribute()]
public static string[] GetCompletionList(string prefixText, int count, string contextKey) {
// Create array of movies
string[] movies = {"Star Wars", "Star Trek", "Superman", "Memento", "Shrek", "Shrek II"};
// Return matching movies
return (from m in movies where m.StartsWith(prefixText,StringComparison.CurrentCultureIgnoreCase) select m).Take(count).ToArray();
}
source: http://www.asp.net/ajaxlibrary/act_autocomplete_simple.ashx
aspx Page Coding
<form id="form1" runat="server">
<input type="search" name="Search" placeholder="Search for a Product..." list="datalist1"
required="">
<datalist id="datalist1" runat="server">
</datalist>
</form>
.cs Page Coding
protected void Page_Load(object sender, EventArgs e)
{
autocomplete();
}
protected void autocomplete()
{
Database p = new Database();
DataSet ds = new DataSet();
ds = p.sqlcall("select [name] from [stu_reg]");
int row = ds.Tables[0].Rows.Count;
string abc="";
for (int i = 0; i < row;i++ )
abc = abc + "<option>"+ds.Tables[0].Rows[i][0].ToString()+"</option>";
datalist1.InnerHtml = abc;
}
Here Database is a File (Database.cs) In Which i have created on method named sqlcall for retriving data from database.

Categories