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.
Related
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 have an existing code that displays a reportserver RDL report in a reportviewer. I prompt the user for inputs and those are then passed as parameters to a store procedure in Sql Server.
The report generates properly as proof of concept with hard-coded number of textboxes, but obviously not all reports will have the same number of parameters. So here is my working code and the screenshot:
Working Report
ASP.NET
<%# Page Language="C#" Trace="true" AutoEventWireup="true" CodeBehind="Reports.aspx.cs" Inherits="FormsAuthAd.Reports" %>
<%# Register Assembly="Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" class="reports-body">
<head runat="server">
<title>Reports</title>
<link href="../css/Style.css" rel="stylesheet" />
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div class="params-container container">
<asp:TextBox ID="txtStart" runat="server" placeholder="From Date" class="input-fields"></asp:TextBox>
<asp:TextBox ID="txtEnd" runat="server" placeholder="To Date" class="input-fields"></asp:TextBox>
<asp:TextBox ID="txtBrand" runat="server" placeholder="Brand" class="input-fields"></asp:TextBox>
<asp:TextBox ID="txtSeason" runat="server" placeholder="Season" class="input-fields"></asp:TextBox>
<asp:TextBox ID="txtComp" runat="server" placeholder="Company" class="input-fields"></asp:TextBox>
<asp:TextBox ID="txtLoc" runat="server" placeholder="Location" class="input-fields"></asp:TextBox>
<asp:TextBox ID="txtLine" runat="server" placeholder="Line" class="input-fields"></asp:TextBox>
<asp:Button ID="btnShow" runat="server" OnClick="Button1_Click" Text="Generate" class="input-fields"/>
</div>
<div class="rpt-container container">
<rsweb:ReportViewer ID="rptVwr" runat="server" CssClass="rpt-viewer"></rsweb:ReportViewer>
</div>
</form>
</body>
</html>
CODE BEHIND
private void showReport()
{
rptVwr.Reset();
DataTable dt = GetData(txtStart.Text, txtEnd.Text, txtBrand.Text, txtSeason.Text, txtComp.Text, txtLoc.Text);
rptVwr.Visible = true;
ReportDataSource rds = new ReportDataSource("DataSet2", dt);
rptVwr.LocalReport.DataSources.Add(rds);
rptVwr.LocalReport.ReportPath = "../ReportServer/StockExport.rdl";
ReportParameter[] rptParams = new ReportParameter[]
{
new ReportParameter("StartDate",txtStart.Text),
new ReportParameter("EndDate",txtEnd.Text),
new ReportParameter("Brand",txtBrand.Text),
new ReportParameter("Season",txtSeason.Text),
new ReportParameter("Company",txtComp.Text),
new ReportParameter("Store",txtLoc.Text),
};
rptVwr.LocalReport.SetParameters(rptParams);
rptVwr.LocalReport.Refresh();
}
private DataTable GetData(string fromDate, string toDate, string brandCode, string seasonCode, string compCode, string locCode)
{
DataTable dt = new DataTable();
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings ["ReportServerConnStr"].ConnectionString;
using (SqlConnection cn = new SqlConnection(connStr))
{
SqlCommand cmd = new SqlCommand("sp_valueEntryStock", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#StartDate", SqlDbType.NVarChar).Value = fromDate;
cmd.Parameters.Add("#EndDate", SqlDbType.NVarChar).Value = toDate;
cmd.Parameters.Add("#Season", SqlDbType.NVarChar).Value = seasonCode;
cmd.Parameters.Add("#Brand", SqlDbType.NVarChar).Value = brandCode;
cmd.Parameters.Add("#Company", SqlDbType.NVarChar).Value = compCode;
cmd.Parameters.Add("#Store", SqlDbType.NVarChar).Value = locCode;
cmd.CommandTimeout = 1000;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
}
return dt;
}
protected void Button1_Click(object sender, EventArgs e)
{
showReport();
}
Obviously, I did not want a hard-coded number of textboxes so I tweaked my code to dynamically add textboxes on page load based on a table in Sql Server.Here is my existing code and screenshot:
Page after submitting parameters
CODE BEHIND
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand("SELECT [FieldNum],[FieldName],[AspId],[SqlParameter] FROM [MIS_FieldsMaster]", con))
{
cmd.CommandType = CommandType.Text;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dtable);
int i = 0;
foreach (DataRow dr in dtable.Rows)
{
TextBox tb = new TextBox();
tb.ID = dr["AspId"].ToString().Trim();
stringArray[i] = dr["SqlParameter"].ToString().Trim();
tb.Text = stringArray[i];
ph1.Controls.Add(tb);
i++;
}
}
}
}
private void showReport()
{
rptVwr.Reset();
DataTable dt = GetData();
rptVwr.Visible = true;
ReportDataSource rds = new ReportDataSource("DataSet2", dt);
rptVwr.LocalReport.DataSources.Add(rds);
rptVwr.LocalReport.ReportPath = "../ReportServer/StockExport.rdl";
rptVwr.LocalReport.Refresh();
}
private DataTable GetData()
{
DataTable dt = new DataTable();
int i = 0;
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["ReportServerConnStr"].ConnectionString;
using (SqlConnection cn = new SqlConnection(connStr))
{
SqlCommand cmd = new SqlCommand("sp_valueEntryStock", cn);
cmd.CommandType = CommandType.StoredProcedure;
foreach (TextBox textBox in ph1.Controls.OfType<TextBox>())
{
cmd.Connection = cn;
cmd.Parameters.AddWithValue("#" + stringArray[i], textBox.Text);
i++;
}
cmd.CommandTimeout = 1000;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
}
return dt;
}
protected void Button1_Click(object sender, EventArgs e)
{
showReport();
}
So it does not even show me any error message so I do not really know where to look. I debugged the new code and I believe it is retrieving the data in the stored procedure because the local variable shows rows retrieved under datatable dt. The only thing is the report does not show in the reportViewer. It does not even show report toolbars.
Row retrieved from datatable dt
I would greatly appreciate any help. Thanks.
I figured out the reason for the report not displaying in the reportviewer.
It seems that I still need to add the parameters and set it to the reportviewer, like in my first working code:
ReportParameter[] rptParams = new ReportParameter[]
{
new ReportParameter("StartDate",txtStart.Text),
new ReportParameter("EndDate",txtEnd.Text),
new ReportParameter("Brand",txtBrand.Text),
new ReportParameter("Season",txtSeason.Text),
new ReportParameter("Company",txtComp.Text),
new ReportParameter("Store",txtLoc.Text),
};
rptVwr.LocalReport.SetParameters(rptParams);
Obviously =, it still needs to be dynamic so here is the code that I used:
List<ReportParameter> paramList = new List<ReportParameter>();
int i = 0;
foreach (TextBox textBox in ph1.Controls.OfType<TextBox>())
{
paramList.Add(new ReportParameter(stringArray[i], textBox.Text));
i++;
}
rptVwr.LocalReport.SetParameters(paramList);
Now, I am able to generate the dynamic textboxes and at the same time pass the values in those textboxes to my sql server stored procedure and finally generate and display the report based on the same textboxes.
I would consider this solved, but I just have a niggling question in my head:
Why didn't my code work when it is exactly the same (at least logically if not syntactically) as the code in the youtube example that I took: Two way to pass parameter in stored procedure and display the output in Report Viewer using C#
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 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!
I've created a search function with 3 DropDownLists and a search button. How will I display it on the same page?
Here's my code:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//read sql server connection string from web.config file
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_province ORDER BY PROVINCE_NAME ASC", conn);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
ddlProvince.DataSource = dt;
ddlProvince.DataTextField = "PROVINCE_NAME";
ddlProvince.DataValueField = "PROVINCE_CODE";
ddlProvince.DataBind();
}
}
protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
PROVINCE_CODE = '" + ddlProvince.SelectedValue + "'", conn);
SqlCommand comm = new SqlCommand("SELECT * FROM emed_city WHERE PROVINCE_CODE =#pcode", conn);
comm.Parameters.AddWithValue("#pcode", ddlProvince.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#pcode";
param.Value = ddlProvince;
comm.Parameters.Add(param);
}
ddlCity.DataSource = dt;
ddlCity.DataTextField = "CITY_NAME";
ddlCity.DataValueField = "CITY_CODE";
ddlCity.DataBind();
}
protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_city");
using (conn)
{
conn.Open();
PROVINCE_CODE = '" + ddlProvince.SelectedValue + "'", conn);
SqlCommand comm = new SqlCommand("SELECT * FROM emed_doctors_hospitals WHERE CITY_CODE =#ccode", conn);
comm.Parameters.AddWithValue("#ccode", ddlCity.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#ccode";
param.Value = ddlCity;
comm.Parameters.Add(param);
}
ddlSched.DataSource = dt;
ddlSched.DataTextField = "SCHEDULE";
ddlSched.DataValueField = "HOSPITAL_CODE";
ddlSched.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
}
}
When someone selects a value in the DropDownList and hits the button, it will display the lists of doctors available in the province, city and per particular schedule.
Check this sample. I have used SQLDatasource with SelectParameters for this example (you
can replace it with your own object datasource, custom binding etc.) SQLDataSource Select Parameters
The second dropdownlist automatically populates when the first dropdownlist is changed
On Button even I am just selecting the currently selected values of each dropdownlist (You can select your doctor list in the same way)
ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Cascading DropDown.aspx.cs"
Inherits="Cascading_DropDown" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">
<title></title> </head> <body>
<form id="form1" runat="server">
<div>
<label>
Category:</label>
<asp:DropDownList ID="ddlCategories" runat="server" AppendDataBoundItems="True" AutoPostBack="True"
DataSourceID="sdsCategory" DataTextField="CategoryName" DataValueField="CategoryID"
OnSelectedIndexChanged="ddlCategories_SelectedIndexChanged">
<asp:ListItem Text="-Select-" Value="" />
</asp:DropDownList>
<br />
<label>
Products:</label>
<asp:DropDownList ID="ddlProducts" runat="server" DataSourceID="sdsProducts" DataTextField="ProductName"
DataValueField="ProductID">
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Search Prodcut" OnClick="Button1_Click" />
<asp:Label ID="lblSelectedValues" runat="server"></asp:Label>
</div>
<asp:SqlDataSource ID="sdsCategory" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [CategoryID], [CategoryName] FROM [Categories] ORDER BY [CategoryName]">
</asp:SqlDataSource>
<asp:SqlDataSource ID="sdsProducts" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [ProductID], [ProductName] FROM [Alphabetical list of products] WHERE ([CategoryID] = #CategoryID)">
<SelectParameters>
<asp:ControlParameter ControlID="ddlCategories" Name="CategoryID" PropertyName="SelectedValue"
Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</form> </body> </html>
.CS
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ddlCategories_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlCategories.SelectedValue == "")
{
ddlProducts.Items.Clear();
ddlProducts.SelectedIndex = -1;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
lblSelectedValues.Text = "You selected Category:" + ddlCategories.SelectedItem.Text + " & prodcut:" + ddlProducts.SelectedItem.Text;
}
You can drop a gridview on form like Abel said & on your button click event, fetch each drop down list selected value & execute your query & databaind your gridview like you are already doing with your drop down lists.
All you essentially need to do is to place the controls in the ASPX page declaratively:
<asp:DropDownList id="ddlSche" runat="server" />
You can calculate the results in the Page_Load using ddlSched.SelectedValue and similar methods.
Essentially, you use the button's onclick handler for this type of thing:. But since you already have a SelectedIndexChanged event, it seems that you're on the right track. It's fired when the user postbacks the page and the index was changed (or, in other words, the user selected something else than the current selection in the DropDownList).