I am using linq to fetch from database to populate in drop down list in asp.net using below code:
XXXDataContext summary = new XXXDataContext();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var binmy = ( from bin in summary SUBPRODUCTs
order by bin.SUBID
select new { bin.SUBID, bin.SUBValue }
);
dropdownsummary.DataValueField = "SUBID";
dropdownsummary.DataTextField = "SUBValue";
dropdownsummary.DataSource = binmy;
DataBind();
}
}
Here I want to include 'All' as default value how to do that?
Add this item in the html dropdown declaration and set the 'AppendDataBoundItems' property to true. See below...
<asp:DropDownList ID="dropdownsummary" runat="server" AppendDataBoundItems="true">
<asp:ListItem Selected="True" Value="-1" Text="All"></asp:ListItem>
</asp:DropDownList>
Use:
dropdownsummary.DataBind();
Instead of :
DataBind();
Try This
dropdownsummary.DataValueField = "SUBID";
dropdownsummary.DataTextField = "SUBValue";
dropdownsummary.DataSource = binmy;
dropdownsummary.Items.Insert("0", new ListItem ( "All" , "0" ));
Related
I have a DropDownList:
<asp:DropDownList class="form-control" runat="server" ID="ddlChangeStatus">
<asp:ListItem Text="Under Review" value="1" />
<asp:ListItem Text="Approved" value="2" />
<asp:ListItem Text="Rejected" value="3" />
<asp:ListItem Text="Logged" value="4" />
<asp:ListItem Text="Completed" value="5" />
</asp:DropDownList>
that when it changes, I want to refresh the gridview with the new value of the DropDownList.
protected void Page_Load(object sender, EventArgs e)
{
using (dbPSREntities5 myEntities = new dbPSREntities5())
{
int theStatus = Convert.ToInt32(ddlChangeStatus.SelectedValue); <--- this is the value of the DropDownList
var allDepartments = (from tbProject in myEntities.tbProjects
// inner join to department lookup table
from refDepartments in myEntities.refDepartments.Where(x => x.refDepartmentID == tbProject.refDepartmentID) // to do a left join instead of an inner, append .DefaultIfEmpty() after this where clause
from refBuildings in myEntities.refBuildings.Where(x => x.refBuildingID == tbProject.refBuildingID).DefaultIfEmpty()
//from tbBreadCrumb in myEntities.tbBreadCrumbs.Where(x => x.ProjectID == tbProject.ProjectID)
from tbBreadCrumb in myEntities.tbBreadCrumbs.Where(x => x.ProjectID == tbProject.ProjectID && x.BreadCrumbID == myEntities.tbBreadCrumbs.Where(y => y.ProjectID == tbProject.ProjectID).Max(y => y.BreadCrumbID) && x.StatusID == theStatus) <---- Here is where the DropDownList value alters the query
from refBreadCrumb in myEntities.refBreadCrumbs.Where(x => x.refBreadCrumbID == tbBreadCrumb.StatusID)
// select new anon type
select new
{
ProjectID = tbProject.ProjectID,
Status = refBreadCrumb.BreadCrumbValue,
DateSubmitted = tbBreadCrumb.CreateDateTime,
refDepartmentID = tbProject.refDepartmentID,
refBuildingValue = refBuildings.refBuildingValue,
ProjectContactFullName = tbProject.ProjectContactFirstName + " " + tbProject.ProjectContactLastName,
ProjectWorkType = tbProject.ProjectWorkType,
refDepartmentValue = refDepartments.refDepartmentValue,
}); // I chose to turn the result into a list to demonstrate something below, you can leave it as an enumerable.
// bind to your listview, make sure control name is accurate and ItemTemplates are defined for each data column.
projectsListView.DataSource = allDepartments;
projectsListView.DataBind();
}
}
Not sure the best way to do this. I tried calling the Page_Load() but that didn't work. Basically just want the user to make a new slection that submits to the page load, that runs the query that refreshes the gridview. Thanks in advance!
Firstly, in the DropDownList control, you need to add AutoPostBack="true"
Secondly, you can do exactly what you are doing in the Page_Load event inside the DropDownList_SelectedIndexChanged event
I hope this helps.
Below code can help you.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostback)
// Bind the data to Gridview as ur business logic
}
protected void ddlChangeStatus_SelectedIndexChanged(object sender, EventArgs e)
{
// Bind the data to Gridview as ur business logic
}
I have a text box and a RadComboBox like this :
<asp:TextBox ID="txt_inner_emp_num" runat="server" Width="60px"
ontextchanged="txt_inner_emp_num_TextChanged" AutoPostBack="true"></asp:TextBox>
<telerik:RadComboBox ID="rad_ddl_inner_emp_name" runat="server" CausesValidation="False"
CollapseDelay="0" Culture="ar-EG" ExpandDelay="0" Filter="Contains" ItemsPerRequest="100"
MarkFirstMatch="true" Width="380px" EnableAutomaticLoadOnDemand="True" EmptyMessage="-emp name-" ShowMoreResultsBox="True" AutoPostBack="True">
</telerik:RadComboBox>
According to the Telerik Documentation
Set a data source to the RadComboBox. Use either DataSourceID or the
DataSource property to do this and set the DataTextField and
DataValueField properties to the respective fields in the data source.
(Note that when using DataSource you must set the property on each
postback, most conveniently in Page_Init.) Set
EnableAutomaticLoadOnDemand to true.
protected void BindEmployees()
{
rad_ddl_inner_emp_name.Items.Clear();
rad_ddl_inner_emp_name.DataSource = Utilities.GetAllEmployees();
rad_ddl_inner_emp_name.DataTextField = "name";
rad_ddl_inner_emp_name.DataValueField = "emp_num";
rad_ddl_inner_emp_name.DataBind();
}
protected void Page_Init(object sender, EventArgs e)
{
BindEmployees();
}
protected void txt_inner_emp_num_TextChanged(object sender, EventArgs e)
{
rad_ddl_inner_emp_name.ClearSelection();
rad_ddl_inner_emp_name.Items.FindItemByValue(txt_inner_emp_num.Text.TrimEnd()).Selected = true;//Get exception here Object reference not set to an instance of an object.
}
I find rad_ddl_inner_emp_name.Items.Count = 0 !! before set the selection ! How to fix this problem ?
As I'm sure you aware of by now, the radcombox typeahead functionality searches text via client side interaction and not by value, which is why you can't find the values.
What I would suggest is having a secondary object to search by emp_num (assuming that's the value that will always be entered into the textbox).
For example, create a global variable:
private Dictionary<string, string> Emp_Dict = new Dictionary<string, string>();
Then populate this dictionary when you do your binding. The following code assumes an ienumerable type being returned. If not you may have to populate the dictionary differently. Also, for this to work, you have to include (System.Linq).
var dataSource = Utilities.GetAllEmployees();
Emp_Dict = dataSource.ToDictionary(ex => ex.emp_num, ex => ex.name);
rad_ddl_inner_emp_name.Items.Clear();
rad_ddl_inner_emp_name.DataSource = dataSource;
rad_ddl_inner_emp_name.DataTextField = "name";
rad_ddl_inner_emp_name.DataValueField = "emp_num";
rad_ddl_inner_emp_name.DataBind();
So now we need to use the dictionary on the text changed event.
protected void txt_inner_emp_num_TextChanged(object sender, EventArgs e)
{
rad_ddl_inner_emp_name.ClearSelection();
if (Emp_Dict.ContainsKey(txt_inner_emp_num.Text.TrimEnd()))
{
rad_ddl_inner_emp_name.SelectedValue = txt_inner_emp_num.Text.TrimEnd();
rad_ddl_inner_emp_name.Text = Emp_Dict[txt_inner_emp_num.Text.TrimEnd()];
}
}
Now when the text changes in the text box, the radcombobox will update when a valid emp_num is entered into the textbox.
The Problem is that the Items only get loaded when you request them!
Set
EnableAutomaticLoadOnDemand="False"
and it will work!
UPDATE:
if you want to use LoadOnDemand set these two Properties and delete the EnableAutomicLoadOnDemand!
EnableLoadOnDemand="True"
EnableItemCaching="True"
UPDATE 2:
Enable ItemCaching isn´t necessary, but it doesn´t hurt!
You do not need to bind data to RadComboBox on every postback unless you disable the view state.
Filter, MarkFirstMatch and EnableAutomaticLoadOnDemand are not useful in your case as you are loading all employees by yourself.
LoadOnDemand basically is when user starts typing inside ComboBox, ComboBox fires ItemsRequested event and retrieves data via ajax.
<asp:TextBox ID="txt_inner_emp_num" runat="server" Width="60px"
ontextchanged="txt_inner_emp_num_TextChanged" AutoPostBack="true" />
<telerik:RadComboBox ID="rad_ddl_inner_emp_name" runat="server"
CausesValidation="False" Culture="ar-EG">
</telerik:RadComboBox>
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
rad_ddl_inner_emp_name.DataSource = Utilities.GetAllEmployees();
rad_ddl_inner_emp_name.DataTextField = "name";
rad_ddl_inner_emp_name.DataValueField = "emp_num";
rad_ddl_inner_emp_name.DataBind();
}
}
protected void txt_inner_emp_num_TextChanged(object sender, EventArgs e)
{
string value = txt_inner_emp_num.Text;
if(!string.IsNullOrWhiteSpace(value))
{
value = value.Trim();
if (rad_ddl_inner_emp_name.Items
.FindItemByValue(txt_inner_emp_num.Text.Trim()) != null)
rad_ddl_inner_emp_name.SelectedValue = value;
}
}
Since you don't have any item in rad_ddl_inner_emp_name.Items you can set txt_inner_emp_num.Text as selected in ddl.
First check if rad_ddl_inner_emp_name.Items count > 0 then set desired text selected. Or you can check if rad_ddl_inner_emp_name.Items.FindItemByValue(txt_inner_emp_num.Text.TrimEnd()) is not null.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Display DB values in a dropdownlist
I am fetching DB values and displaying them in the Dropdown list. I have country and state drop down lists:
DropDownList1.Items.Add(new ListItem(Session["country"].ToString()));
DropDownList2.Items.Add(new ListItem(Session["state"].ToString()));
I am unable to show the DB values in the DDL. I am getting --select a state--
in the state Dropdown list how to show the DB values in the Dropdown list?
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True">
<asp:ListItem Value="Select a state" >Select a state</asp:ListItem>
<asp:ListItem Value="value 1" >Maharastra</asp:ListItem>
<asp:ListItem Value="value 2" >Goa</asp:ListItem>
<asp:ListItem Value="value 3" >Kashmir</asp:ListItem>
</asp:DropDownList>
i am cacthing the DB values here and sending them to the next page
if (dt.Rows.Count > 0)
{
DataTable dt1 = new DataTable();
dt1 = bll.getnewid(TextBox1.Text);
if (dt1.Rows.Count > 0)
{
Session["country"] = dt1.Rows[0]["Country"].ToString();
Session["state"] = dt1.Rows[0]["State"].ToString();
Well, you must somehow bind your ddlist to the db results. Looks like this:
ddlist1.DataSource = MyDBAccessClass.GetSomeValues();
ddlist1.DataBind();
Based on more comments... I'll have to play a little roulette and guess what's your intentions. Your code has multiple problems and you've obviously some issues explaining yourself.
If I understood you correctly, you have 2 dropdownlists. You want to populate one with countries and based on the selection, populate the second dropdownlist.
The basic principle looks like this:
DataAccessClass.cs
public class DataAccessClass
{
public static IEnumerable<string> GetCountries()
{
// access the database and retrieve all the values
// returns IEnumerable (a list of items)
}
public static IEnumerable<string> GetStates(string selectedCountry)
{
// access the database and retrieve all the corresponding states
// linq2sql: var states = from o in db.States
// where o.country = selectedCountry
// select o;
// returns IEnumerable (a list of items)
}
}
YourPage.aspx
<asp:DropDownList id="ddlistCountries" runat="server" AutoPostBack="True" /><br />
<asp:DropDownList id="ddlistStates" runat="server" />
YourPage.aspx.cs
public partial class YourPage
{
protected void Page_Init(object sender, EventArgs e)
{
ddlistCountries.SelectedIndexChanged += new EventHandler(ddlist_SelectedIndexChanged);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!isPostBack)
{
PopulateCountries();
ddlistStates.Enabled = false; // no country selected yet!
}
}
protected void PopulateCountries()
{
ddlistCountries = DataAccessClass.GetCountries();
ddlistCountries.DataBind();
ddlist.Items.Insert(0, "Select a country");
}
void ddlist_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlistCountries.SelectedIndex != 0)
{
ddlistStates.DataSource = DataAccessClass.GetStates(ddlistCountries.SelectedValue);
ddlistStates.DataBind();
ddlistStates.Enabled = true;
}
else
{
ddlistStates.Items.Clear();
ddlistStates.Enabled = false;
}
}
}
If you can't understand this, either go back to basics or forget about programming altogether.
DropDownList2.DataSource = {your data source};
DropDownList2.DataTextField = "text column name";
DropDownList2.DataValueField = "data column name of id";
DropDownList2.DataBind();
You need to set your data source to the DDL, then set which values to display, then bind it.
I would suggest to use the dropdownlist like this :
ddl.DataSource = YourDBSource.Get();
ddl.DataBind();
you can then decide what to be displayed here with :
ddl.DataTextField = ...;
or
ddl.DataValueField = ...;
First of all, there is no reason to build your listItem in the .aspx page because you will populate your ddl programmatically.
Secondly I don't know what you mean by 'i am cacthing the DB values here and sending them to the next page'. Just fill the dataSource with the appropriate query on you DB.
If you want to perform more easy filtering / wahtever you want, try to use Linq2SQL.
Additionally, you need to perform this databinding in the *Page_Load()* like this :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlErreur.DataSource = ...;
ddlErreur.DataTextField = ...;
ddlErreur.DataBind();
}
}
I have 2 list boxes.
<asp:ListBox ID="ListBox_Region" runat="server"
DataTextField="arregion" DataValueField="arregion" AutoPostBack="True"
Height="96px"
Width="147px" DataSourceid="sqldatasource1"></asp:ListBox>
<asp:ListBox ID="ListBox_Area" runat="server"
DataTextField="ardescript" DataValueField="ardescript"
AutoPostBack="True"
OnSelectedIndexChanged="ListBox_Area_SelectedIndexChanged"
Height="96px"
Width="147px" >
So, when I select a value from ListBox_Region , the corresponding values get updated in ListBox_Area in this way:
protected void ListBox_Region_SelectedIndexChanged(object sender, EventArgs e)
{
this.ListBox_Area.Items.Clear();
string selectedRegion = ListBox_Region.SelectedValue;
var query = (from s in DBContext.areas
where s.arregion == selectedRegion
select s);
ListBox_Area.DataSource = query;
ListBox_Area.DataBind();
}
The event for ListBoxRegion_SelectedIndexChaged is written in page Load.
However, the problem is on initial page load, where the first value of ListBox_Region should be Selected by default. The second listbox should be updated to corresponding values but this should happen before selected index changed gets fired. So, can u please let me know how to do this?
Move the logic on ListBox_Region_SelectedIndexChanged to a separated method and call it from page_load when postback is false.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
// Bind ListBox_Region and set the first value as selected
...
//
BindAreaList();
}
}
protected void ListBox_Region_SelectedIndexChanged(object sender, EventArgs e)
{
BindAreaList();
}
protected void BindAreaList()
{
this.ListBox_Area.Items.Clear();
string selectedRegion = ListBox_Region.SelectedValue;
var query = (from s in DBContext.areas
where s.arregion == selectedRegion
select s);
ListBox_Area.DataSource = query;
ListBox_Area.DataBind();
}
I have one asp.net application, in which i have one dropdown which is binded to dataset. But after selecting one item, the drop down gets cleared all the value, How we can resolve this issue?
This is my dropdown list in design page:
<asp:DropDownList ID="ddlProduct" runat="server" CssClass="textEntry" Width="300px"
AutoPostBack="True" OnSelectedIndexChanged="ddlProduct_SelectedIndexChanged">
</asp:DropDownList>
and binding code is shown below.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindProductDdl();
}
private void BindProductDdl()
{
Products objProducts = new Products();
dsProducts dsProduct = new dsProducts();
ListItem olst = default(ListItem);
olst = new ListItem(" Select", "0");
dsProduct = objProducts.GetDataset("");
ddlProduct.DataSource = dsProduct;
ddlProduct.DataTextField = "Product";
ddlProduct.DataValueField = "Id";
ddlProduct.DataBind();
ddlProduct.Items.Insert(0, olst);
}
protected void ddlProduct_SelectedIndexChanged(object sender, EventArgs e)
{
Products objProducts = new Products();
dsProducts dsProduct = new dsProducts();
string criteria = "";
if (ddlProduct.SelectedItem.Text != " Select")
{
string id = ddlProduct.SelectedItem.Value;
criteria = "Id='" + id + "'";
dsProduct = objProducts.GetDataset(criteria);
productValue = Convert.ToDecimal(dsProduct.tblProducts.Rows[0]["Value"].ToString());
}
}
Thanks in advance..
From your question if I understand correctly you dont want the dropdown list to rebind if it is populated. Also please check your viewstate, this should not be happening, unless you have disabled viewstate
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack && ddlProduct.Items.count <=0 )
BindProductDdl();
}
Set the AppendDataBoundItems property of the dropdown to true and this will allow you to have a mix of databound items and non databound items (otherwise that insert statement is clearing your list)
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.appenddatabounditems.aspx
Do you have viewstate disabled on the page? Since you are only loading the items into the dropdownlist on the first load of the page, if viewstate is not enabled there will be nothing in the list after the postback.
Not positive, but I've seen in other languages and false interpretation...
You have your product Value as convert of ToDecimal which implies 99.999 for example.
If your ID that you are binding to is based on a whole number (ie: Integer basis), the bound value won't match... even if Value = 1 vs Value = 1.00 it won't match and will not be considered a valid "value" that matches your list. Convert your answer to a whole/integer number and it might do what you expect.
Without seeing the full source for the page I am simply speculating, but have you disabled ViewState on the page? If so, the DropDownList cannot retain its values between postbacks and the lists will have to be reloaded each time.