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
}
Related
I've got an asp.net webforms page which has a drop down filled with Categories. If the user selects the Category "ER" or "DR", a Description textbox will be populated based on which one is chosen. However, I need to inform the user that their text in the Description field will be lost if they switch categories.
submit_ticket.aspx
function ShowConfirmation(ddlCategory) {
//Not sure what goes here.
}
<asp:DropDownList ID="ddlCategory" runat="server" CssClass="DropDownList" OnSelectedIndexChanged="ddlCategory_SelectedIndexChanged" AutoPostBack="true" />
Submit_ticket.aspx.cs
protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
{
if (IsPostBack)
{
if ((ddlCategory.SelectedItem.Text == "DR") || ddlCategory.SelectedItem.Text == "ER")
ddlCategory.Attributes.Add("onChange", "return ShowConfirmation(this);");
if (ddlCategory.SelectedItem.Text == "DR")
txtDescription.Text = "DR Template";
else if (ddlCategory.SelectedItem.Text == "ER")
txtDescription.Text = "ER Template";
}
}
There are 7 Categories in total but I only need this functionality on the two listed above. The "template" used for those Categories is long and it can't be an option to populate the Description textbox with Javascript.
Any help is greatly appreciated.
Remove the AutoPostBack from the dropdown and add your own js function to the onchange event.
<asp:DropDownList ID="DropDownList1" runat="server" onchange="func();">
<asp:ListItem Text="01"></asp:ListItem>
<asp:ListItem Text="02"></asp:ListItem>
<asp:ListItem Text="03"></asp:ListItem>
</asp:DropDownList>
In your js function get a response from the user. If 'yes', force a postback using the __doPostBack function built-in to asp.net. Include the name of the control and 'true' as parameters.
function func() {
if (confirm("change?")) {
// parameters are: '__EVENTTARGET' and '__EVENTARGUMENT'.
__doPostBack("DropDownList1", "true");
}
}
Check the __EVENTARGUMENT when the page loads.
protected void Page_Load(object sender, EventArgs e)
{
if(Request.Params.Get("__EVENTARGUMENT") == "true")
{
// call a method.
TextChanger();
}
}
protected void TextChanger()
{
if (DropDownList1.SelectedItem.Text == "02")
{
Label2.Text = "changed text";
}
}
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" ));
i have a datalist contains checkboxlist.
<asp:DataList ID="dtlstfilter" runat="server">
<ItemTemplate>
<asp:CheckBoxList ForeColor="Gray" AutoPostBack="true" OnSelectedIndexChanged="chklist_SelectedIndexChanged" ID="chklist"
runat="server">
</asp:CheckBoxList>
</ItemTemplate>
</asp:DataList>
when i check one from the checkbox list in the SelectedIndexChanged event i got the selected value using
CheckBoxList c = (CheckBoxList)sender;
string selectedvalue= c.SelectedValue;
likewise how can get the value from a checkboxlist if i uncheck one from the checkboxlist
The SelectedIndexChanged gets also fired if you uncheck a CheckBox. So it works the same way. But if you want to know the (now) unchecked item(s), you have to store the old selection somewhere, for example in the ViewState:
private IEnumerable<string> SelectedValues
{
get
{
if (ViewState["SelectedValues"] == null && dtlstfilter.SelectedIndex >= -1)
{
ViewState["SelectedValues"] = dtlstfilter.Items.Cast<ListItem>()
.Where(li => li.Selected)
.Select(li => li.Value)
.ToList();
}else
ViewState["SelectedValues"] = Enumerable.Empty<string>();
return (IEnumerable<string>)ViewState["SelectedValues"];
}
set { ViewState["SelectedValues"] = value; }
}
protected void chklist_SelectedIndexChanged(Object sender, EventArgs e)
{
CheckBoxList c = (CheckBoxList)sender;
var oldSelection = this.SelectedValues;
var newSelection = c.Items.Cast<ListItem>()
.Where(li => li.Selected)
.Select(li => li.Value);
var uncheckedItems = newSelection.Except(oldSelection);
}
This should even work if multiple checkboxes can be selected.
You can take the jQuery Route if it suits you...
if (!IsPostBack)
{
foreach (ListItem item in chkList.Items)
{
//adding a dummy class to use at client side.
item.Attributes.Add("class", "chkItem");
}
}
Put one button on your form with style display : none. And a Hidden Field to track the currently checked checkbox.
<asp:Button ID="hdnButton" runat="server" style="display:none;" OnClick="hdnButton_Click"/>
<asp:HiddenField ID="hdnCurrent" runat="server" />
The jQuery Part....
$(".chkItem input:checkbox").change(function(){
$("#hdnCurrent").val($(this).attr("id") + "|" + $(this).attr("checked"));
$("#hdnButton").click();
});
You can use more hidden fields if you don't want to do string operations on backend. Depends on your taste.
Then handle the button click event like below.
protected void hdnButton_Click(object sender, EventArgs e)
{
String[] Value = hdnCurrent.Value.Split('|');
if (Value[1] == "true")
{
//Do operations here when the check box is checked
}
else
{
//Do operations here when the check box is unchecked
}
//Value[0] contains the id of the check box that is checked/unchecked.
}
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();
}