I am displaying columns in a GridView and one of the columns is a dropdownlist. I want to be able to save the option selected in the dropdownlist as soon as something is selected. I have done this with one of the columns that has a textbox so I was hoping to do something similar with the DropDownList.
The code for the textbox and dropdownlist:
protected void gvPieceDetails_ItemDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.DataRow) {
JobPieceSerialNo SerNo = e.Row.DataItem as JobPieceSerialNo;
if (SerNo != null) {
TextBox txtComment = e.Row.FindControl("txtComment") as TextBox;
txtComment.Text = SerNo.Comment;
txtComment.Attributes.Add("onblur", "UpdateSerialComment(" + SerNo.ID.ToString() + ", this.value);");
DropDownList ddlReasons = (e.Row.FindControl("ddlReasons") as DropDownList);
DataSet dsReasons = DataUtils.GetUnapprovedReasons(Company.Current.CompanyID, "", true, "DBRIEF");
ddlReasons.DataSource = dsReasons;
ddlReasons.DataTextField = "Description";
ddlReasons.DataValueField = "Description";
ddlReasons.DataBind();
ddlReasons.Items.Insert(0, new ListItem("Reason"));
}
}
How to I create an update function for a dropdownlist?
protected void DDLReasons_SelectedIndexChanged(object sender, EventArgs e)
{
string sel = ddlReasons.SelectedValue.ToString();
}
public static void UpdateSerialReason(int SerNoID, string Reasons)
{
JobPieceSerialNo SerNo = new JobPieceSerialNo(SerNoID);
SerNo.Reason = sel; //can't find sel value
SerNo.Update();
}
Dropdownlist:
<asp:DropDownList ID="ddlReasons" runat="server" OnSelectedIndexChanged="DDLReasons_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
I created an OnSelectedIndexChanged function to get the selected value. But how do I then save that value? Is there a way to pass it into the UpdateSerialReason function?
Just move the string sel declaration outside the scope of DDLReasons_SelectedIndexChanged and get the Text of the SelectedItem since it's included in your data source.
private string sel;
protected void DDLReasons_SelectedIndexChanged(object sender, EventArgs e)
{
sel = ddlReasons.SelectedItem.Text;
}
public static void UpdateSerialReason(int SerNoID, string Reasons)
{
JobPieceSerialNo SerNo = new JobPieceSerialNo(SerNoID);
SerNo.Reason = sel; // Should now be available
SerNo.Update();
}
The way you had it previously it was only available in the local scope, i.e, inside the method in which it was being declared and used.
You can get selected value when you call your function:
UpdateSerialReason(/*Some SerNoID*/ 123456, ddlReasons.SelectedValue)
You will lose your value after postback is done if you save value to variable as Equalsk suggested. If you need to use your value on the other page you can save it in session.
If you are working within one asp.net page you can do as I suggested above. Then you can skip the postback on your DropDownList and call UpdateSerialReason when you need :)
And you might want to add property ViewStateMode="Enabled" and EnableViewState="true"
Related
I have an asp.net user control with 3 DropDownLists i.e (ddlState, ddlOffice and ddlOfficeType)
ddlState loads all states
ddlOffice loads offices in the selected state
while ddlOfficeType loads office types in the selected office.
In the user control file (.ascx.cs), I have the below on Page_Load.
protected void Page_Load(object sender, EventArgs e)
{
//if (!Page.IsPostBack)
//{
PopulateStates();
Session[PageName + "State"] = ddlState.SelectedValue;
//}
}
When the state selection changes, I have that event handled as below
protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
{
string previousStateSelection = null;
if (Session["State"] != null)
{
previousStateSelection = Session["State"].ToString();
}
PopulateOffices(int.Parse(ddlState.SelectedValue));
Session[PageName + "State"] = ddlState.SelectedValue;
}
Now when I select a state in the 1st DropDownList, the related offices are populated correctly with the first office in the list selected.
The issue I'm facing is that when I now change the office selection in the 2nd DropDownList such that I load the 3rd DropDownList with office types related to the selected office, my new office selection is not retained on PostBack.
It's like my ddlOffice DropDownList is being refreshed & reset.
In Page_Load, I have no other code that might be reloading the DropDownList.
If I uncomment my check of IsPostBack to the below
if (!Page.IsPostBack)
{
PopulateStates();
Session[PageName + "State"] = ddlState.SelectedValue;
}
Then even the first ddlState does not load anything on PostBack, both ddlState & ddlOffice return empty.
Below is how I'm databinding the DropDownLists:
Load states (All)
private void PopulateStates()
{
if (ddlState.Items.Count > 0)
return;
States = GetStates()
ddlState.ClearSelection();
ddlState.Items.Clear();
ddlState.DataSource = States;
ddlState.DataTextField = "State_Name";
ddlState.DataValueField = "State_ID";
ddlState.DataBind();
}
Load offices based on selected state
private void PopulateOffices(int stateId)
{
var offices = new List<Office>();
offices = GetofficesBystateId(stateId).OrderBy(s => s.OfficeName).ToList();
ddlOffice.ClearSelection();
ddlOffice.Items.Clear();
ddlOffice.DataSource = offices;
ddlOffice.DataTextField = "OfficeName";
ddlOffice.DataValueField = "OfficeId";
ddlOffice.DataBind();
ddlOffice.SelectedIndex = ddlOffice.Items.IndexOf(ddlOffice.Items.FindByText(ddlOffice.Text));
}
Load office types based on selected office
private void PopulateOfficeTypes(int officeId)
{
var officeTypes = GetofficeTypesBySite(officeId);
ddlOfficeType.ClearSelection();
ddlOfficeType.Items.Clear();
ddlOfficeType.DataSource = officeTypes;
ddlOfficeType.DataTextField = "OfficeType";
ddlOfficeType.DataValueField = "OfficeTypeId";
ddlOfficeType.DataBind();
}
In the markup, all DropDownLists have
runat="server" AutoPostBack="True" EnableViewState="true"
2nd DDL's SelectedIndexChanged event handler.
protected void ddlOffice_SelectedIndexChanged(object sender, EventArgs e)
{
PopulateOfficeTypes(int.Parse(ddlOffice.SelectedValue));
Session[PageName + "Office"] = selectedValue;
}
have a radiobutton list which I am filling with Strings and would like to know how to get in a given time the value of the selected element and throw it into a String for example. but with the command SelectedValue and SelectedItem only have null values.
This radio button list is filled several times during the execution of the same page.
//Where do you fill the RadioButtonList
public void MostraImagensCarrefadas()
{
List<String> files = new manFile().getListFilesForDirectory(this, MAE.DIRETORIO_TEMP_IMG);
rbImagemPrincipal.Items.Clear();
if (files != null)
{
foreach (String item in files)
{
rbImagemPrincipal.Items.Add(new ListItem(item));
}
}
}
//As it is in aspx
<div>
<asp:RadioButtonList ID="rbImagemPrincipal" runat="server" RepeatDirection="Vertical" AutoPostBack="false" OnSelectedIndexChanged="rbImagemPrincipal_SelectedIndexChanged"></asp:RadioButtonList>
//where only encounter null values when trying to get the selected item (clicked)
//Nothing I do is the value obtained direferente null.
if (rbImagemPrincipal.SelectedItem != null)
{
if (rbImagemPrincipal.SelectedItem.ToString() == str)
{
imagem.imagemPrincipal = "SIM";
}
}
It seems that you're populating the RadioButtonList on the page load -
If so - make sure you surround your population of the RadioButtonList with an
If/Then/Postback block:
if not Page.IsPostBack then
' populate your RBL
end if
eg:
if (!IsPostBack)
{
loadradiobuttonlist();
}
First of all, this is the page let you know the value, not the application is getting it.
So, you need a ScriptManager and Timer, both are Ajax extensions. Add them to the page.
protected void Page_Load(object sender, EventArgs e)
{
Timer1.Interval = 2000; // set your interval
}
protected void Timer1_Tick(object sender, EventArgs e)
{
int result = RadioButtonList1.SelectedIndex;
}
result is your radiobuttonlist selection index. Use it to select item from list.
I am trying to use two DropDownLists to filter data. I set both of the OnSelectedIndexChanged Equal to the method below. The problem is it is only grabbing the SelectedIndex of the DDL that is changed. Example: if i choose a option in DDL1 it grabs that value and doesnt grab the value of DDL2. They both have the same OnSelectedIndexChanged i figured it would grab the current value of both. Is there a way to make it look at both DDL Controls?
protected void BrandsList_SelectedIndexChanged(object sender, EventArgs e)
{
int DDLcatId = CategoriesList.SelectedIndex;
int DDLBraId = BrandsList.SelectedIndex;
IQueryable<Product> DDLprodResult = GetProductsDDL(DDLcatId, DDLBraId);
if(DDLprodResult == null)
{
}
else
{
CatLab.Text = DDLprodResult.ToList().Count().ToString();
productList.DataSource = DDLprodResult.ToList();
productList.DataBind();
}
}
Your code should work. Of course only one can be changed if you have set AutoPostBack="true"(default is false) on both. But you should get the correct SelectedIndex anyway in the handler.
So i will guess: you are databinding the DropDownLists on every postback. Do this only if(!IsPostBack), otherwise you always overwrite changes with the original values.
So for example in Page_Load:
protected void Page_Load(Object sender, EvengtArgs e)
{
if(!IsPostBack)
{
// DataBind your DropDownLists
}
}
I have a Program Class, with properties as Id, ProgramName,ShortName and Code, im my app
I have a ASP DDL like
<asp:DropDownList ID="DDLProgram" runat="server"
OnSelectedIndexChanged ="OnDDLProgramChanged" AutoPostBack = "true">
</asp:DropDownList>
My OnDDLProgramChanged method is defined as
protected void OnDDLProgramChanged(object sender, EventArgs e)
{
List<CcProgramEntity> programEntities = GetAllPrograms();
DDLProgram.DataSource = programEntities;
DDLProgram.DataTextField = "Shortname";
DDLProgram.DataValueField = "Id";
//My Problem goes here
string programCode = programEntities[DDLProgram.SelectedIndex].Code;
}
My list is getting all the records correctly, I have checked it. But whenever I am changing an item in the DDL, the selected index in not changing. The selected index is remaining zero.Therefore, I am not being able to get the code of other items but the 0 index's item.
Can anyone help me in this case?
You are binding the data again in your selectedIndex Change event and it will reset your current SelectedIndex after rebinding. You don't need to rebind the data to your dropdown in SelectedIndex Change Event
It should be like..
protected void OnDDLProgramChanged(object sender, EventArgs e)
{
string programCode = programEntities[DDLProgram.SelectedIndex].Code;
}
You have to bind data to the DropDownList on page load method
if (!IsPostBack)
{
DDLProgram.DataSource = programEntities;
DDLProgram.DataTextField = "Shortname";
DDLProgram.DataValueField = "Id";
DDLProgram.DataBind();
}
Otherwise it will bind data everytime and hence clear the selection
Why are you assigning the DataSource in OnDDLProgramChanged, this would be resetting the selection you make.
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.